我在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”,但显示错误。
答案 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();
}
}