委托方法VS通用方法 [英] Delegate Methods vs General Methods

查看:209
本文介绍了委托方法VS通用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道的[无代表]使用委托方法,并使用一般方法之间的差异

I want to know the difference between using Delegate Methods and using General Methods[without Delegates].

随着代表:

delegate void DelMethod(string str);

static void Method(string str)
{
    Debug.WriteLine(str);
}

用法:

DelMethod dm = new DelMethod(Method);
dm(string);






并没有委托:

static void Method(string str)
{
    Debug.WriteLine(str);
}

用法:

Method(string)






什么是这两个??


What are the differences of these two??

没有委托该方法是小和容易。但我发现使用委托方法频繁编码器。

The method without delegate is smaller and easy. But I find coders using delegated Methods frequently.

这背后有什么?

推荐答案

代表的是另一种情况。试想一下,你有一个类,它应该回答从另一个类的东西,但你一无所知第二课堂。在这种情况下,你可以先做代表。

Delegates is for another situation. Imagine, that you have a class, which should answer for something from another class, but you know nothing about second class. In such situation you can do Delegate in first.

//class witch should know something
class A
{
   //delegate for answer
   public Func<bool> AskForSomething { get; set; }

   public void DoSomething()
   {
      //some code
      if(AskForSomething())
      {
          //do something
      }
      else
      {
          //do something else
      }
   }
}

class B
{
   public void Test()
   {
      A a = new A();
      a.AskForSomething = new Func<bool>(Answer);
      a.DoSomething();
   }

   private bool Answer()
   {
       return true;
   } 
}



所以,A级一无所知B类,但它可以调用B的方法,并得到它的结果。在B类的回答方法的私人和A类不能直接调用它。

So, class A knows nothing about class B, but it can call B's method and get it's result. Answer method in class B is private and class A can't call it directly.

阅读更多的 MSDN

这篇关于委托方法VS通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆