【发布时间】:2014-02-12 23:18:49
【问题描述】:
我正在尝试理解 C# 中的委托。我知道它们在 linq 等许多场景中是必须的,但是在简单的控制台应用程序中,如果我选择不使用它,我的生活会如此悲惨吗?我不是想逃避它或任何东西。我只是想权衡使用它与不使用它的重要性。例如,我从某个地方抓取了一个 c# 控制台示例。我将如何着手将这个使用委托的优秀程序解构为一个不使用委托的所谓不优雅的版本?
class Program
{
// Define our delegate type: pointer to any method taking in string parameter and returning void
public delegate void Write(string theText);
// Method for output to screen
public static void OutputToScreen(string theText)
{
Console.WriteLine(theText);
}
// Method to output to file
public static void WriteToFile(string theText)
{
StreamWriter fileWriter = File.CreateText("delegatedemo.txt");
fileWriter.WriteLine(theText);
fileWriter.Flush();
fileWriter.Close();
}
public static void Main()
{
// Assign a method to a delegate
Write toFile = new Write(WriteToFile);
Write toScreen = new Write(OutputToScreen);
Display("This is a delegate demo", toFile);
Display("This is a delegate demo", toScreen);
}
public static void Display(string theText, Write outputMethod)
{
outputMethod(theText);
}
}
【问题讨论】:
-
理解代表需要时间。早在过去,计算机科学 101 班会在学科出现指针时失去一半的学生。一个额外的间接级别,需要时间来理解。代表并不像指针那样不透明,所以不要惊慌。继续尝试使用它们,你会得到啊!片刻。没有人可以真正为您加快速度。
标签: c# linq events methods delegates