委托方法与一般方法

4

本文介绍了委托方法与一般方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想知道使用委托方法和使用通用方法[无委托]之间的区别.

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.

这背后的原因是什么??

What is the reason behind this??

推荐答案

代表是另一种情况.想象一下,你有一个班级应该回答另一个班级的问题,但你对第二个班级一无所知.在这种情况下,您可以先做一个委托.

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

// class where you 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;
   } 
}

Class Aclass B一无所知,但它可以调用B的方法并得到它的结果.class B中的Answer方法是privateclass A不能直接调用.

Class A knows nothing about class B, but it can call B's methods and get it's results. The Answer method in class B is private and class A can't call it directly.

在 MSDN

这篇关于委托方法与一般方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14