Хранение значений от делегатов - PullRequest
0 голосов
/ 29 февраля 2020

если у меня есть делегат, а затем я добавляю к нему несколько методов, как мне сохранить каждое возвращаемое значение отдельно?

скажем, например, у меня было что-то вроде ниже, что мне нужно сделать, чтобы оба значения из обоих методов, чтобы я мог отобразить их в методе PlayWithDelegate, просто установить массив stati c и сохранить там результаты или есть какой-то другой способ?

public delegate string EnterName();

internal class Class1
{
    //Our delegate
    public delegate string EnterName();

    static void Main(string[] args)
    {
        EnterName testname = Getname;
        testname += GetAge;
        PlayWithDelegate(testname());
    }

    private static string GetAge()
    {
        Console.WriteLine("Please enter your age : ");
        string result = Console.ReadLine();
        if (result == "") result = " a mystery";
        return result;
    }

    private static void PlayWithDelegate(string name)
    {
        Console.WriteLine( "your name is {0} and age is {1}",name, name );
        Console.ReadLine();
    }

    public static string Getname( )
    {
        Console.WriteLine("Please enter your name : ");
        string result = Console.ReadLine();
        if (result == "") result = " a mystery";
        return result;
    }
}

1 Ответ

0 голосов
/ 29 февраля 2020

Вы можете сохранить их как отдельные значения. Я внес небольшое изменение в ваше решение.

В вашем коде вы переназначаете делегат функции другому, и он заменяет предыдущее значение. Вот почему в результате отображаются только возраст, а не имя и возраст.

В измененном коде я гарантирую, что я оставляю оба делегата назначенными для функций и держу их раздельными, а затем вызываю этих делегатов в функции PlayWithDelegate.

public delegate string UserInput();

internal class Class1
{
    static void Main(string[] args)
    {
        UserInput name = Getname;
        UserInput age = GetAge;
        PlayWithDelegate(name, age);
    }

    private static string GetAge()
    {
        Console.WriteLine("Please enter your age : ");
        string result = Console.ReadLine();
        if (result == "") result = " a mystery";
        return result;
    }

    private static void PlayWithDelegate(UserInput name, UserInput age)
    {
        Console.WriteLine("your name is {0} and age is {1}", name(), age());
        Console.ReadLine();
    }

    public static string Getname()
    {
        Console.WriteLine("Please enter your name : ");
        string result = Console.ReadLine();
        if (result == "") result = " a mystery";
        return result;
    }
}

Вы также упомянули о возможном сохранении результатов в какую-то коллекцию, вы также можете сделать это ...

public delegate string UserInput();

internal class Class1
{

    static void Main(string[] args)
    {
        UserInput[] inputs = new UserInput[] { Getname, GetAge };       
        string[] results = inputs.Select(func => func()).ToArray();     
        PlayWithDelegate(results);
    }

    private static string GetAge()
    {
        Console.WriteLine("Please enter your age : ");
        string result = Console.ReadLine();
        if (result == "") result = " a mystery";
        return result;
    }

    private static void PlayWithDelegate(string[] results)
    {
        Console.WriteLine("your name is {0} and age is {1}", results[0], results[1]);
        Console.ReadLine();
    }

    public static string Getname()
    {
        Console.WriteLine("Please enter your name : ");
        string result = Console.ReadLine();
        if (result == "") result = " a mystery";
        return result;
    }
}
...