代表们应该显示文字

时间:2018-05-24 17:01:42

标签: c#

我在c#中有以下代码:

public class FClass
{
    public delegate string Show(int n);

    public void ShowDelegate(Show SD)
    {
        SD(1);
    }
}

public class SClass
{
    static string ReturnString(int n)
    {
        return n.ToString();
    }
    static void Main(string[] args)
    {
        FClass fclass = new FClass();
        FClass.Show show = new FClass.Show(ReturnString);
        Console.WriteLine(fclass.ShowDelegate(show));
    }
}

它应显示“1”,但显示错误。

2 个答案:

答案 0 :(得分:1)

ShowDelegate()函数不返回任何值。您需要它来返回SD委托的值:

public class FClass
{
    public delegate string Show(int n);
    public string ShowDelegate(Show SD)
    {
        return SD(1);
    }
}

public class SClass
{
    static string ReturnString(int n)
    {
        return n.ToString();
    }

    static void Main(string[] args)
    {
        FClass fclass = new FClass();
        FClass.Show show = new FClass.Show(ReturnString);
        Console.WriteLine(fclass.ShowDelegate(show));
    }
}

答案 1 :(得分:-1)

Krypt1所述,ShowDelegate()函数不会返回任何值(void)。你需要它来从SD代表返回值或将Console.WriteLine调用移到ShowDelegate方法:

public class FClass
{
    public delegate string Show(int n);
    public void ShowDelegate(Show SD)
    {
        Console.WriteLine(SD(1)); // <-- Show delegate text
    }
}
public class SClass
{
    static string ReturnString(int n)
    {
        return n.ToString();
    }
    static void Main(string[] args)
    {
        FClass fclass = new FClass();
        FClass.Show show = new FClass.Show(ReturnString);
        fclass.ShowDelegate(show);
        Console.ReadKey();
    }
}