【发布时间】:2014-03-26 22:16:06
【问题描述】:
以下代码行我无法完全弄清楚它为什么起作用。
--> var blogDelegate = new **Document.SendDoc(blogPoster.PostToBlog);**
SendDoc 没有参数 列表但仍然有效,我不确定为什么会这样。 SendDoc 是返回和 int 且不带参数的委托,但在上面的示例中,SendDoc 有一个 blogPoster.PostToBlog 参数,为什么必须使用 new 关键字来创建委托的实例。这一点我也不确定。我可以看到 Document 的创建和实例,但没有看到创建委托方法实例的原因。
**问题:当委托int SendDoc()声明没有参数列表时,为什么Document.SendDoc(blogPoster.PostToBlog)在参数列表中有参数。
代码:
class Program
{
static void Main(string[] args)
{
Document doc = new Document();
doc.Text = "Document text goes here...";
var blogPoster = new BlogPoster();
var blogDelegate = new Document.SendDoc(blogPoster.PostToBlog);
doc.ReportSendingResult(blogDelegate);
var emailSender = new EmailSender();
var emailDelegate = new Document.SendDoc(emailSender.SendEmail);
doc.ReportSendingResult(emailDelegate);
Console.ReadKey();
}
}
class Document
{
public string Text { get; set; }
public delegate int SendDoc();
public void ReportSendingResult(SendDoc sendingDelegate)
{
if (sendingDelegate() == 0)
{
Console.WriteLine("Success");
}
else
{
Console.WriteLine("Unable to send!");
}
}
}
public class EmailSender
{
private int sendResult;
public int SendEmail()
{
Console.WriteLine("Simulating sending email...");
return sendResult;
}
}
public class BlogPoster
{
public int PostToBlog()
{
Console.WriteLine("Posting to blog...");
return 0;
}
}
}
【问题讨论】:
-
Document在哪个程序集中运行?这是 MS Office 的一部分吗? -
您误解了代表的工作方式。当您创建委托对象时,您必须提供委托的目标。该参数不是可选的,它是方法的 name。当您调用委托时,您必须提供目标方法参数。在你的情况下没有。
标签: c#