简体   繁体   English

方法是否转换为委托?

[英]Do methods are transformed into delegates?

My understanding of delegates is that delegate is a special object that containts sequence of pointers to methods (each method should have the same return type and parameters).我对委托的理解是委托是一个特殊的 object 包含指向方法的指针序列(每个方法应该具有相同的返回类型和参数)。

Lets consider that we defined delegate like that让我们考虑一下我们这样定义委托

delegate int MyDelegate(string name, int age);

We can use it later in code like that我们可以稍后在这样的代码中使用它

// creating the instance of delegate
MyDelegate objDelegate = null;

// initialising that instance
objDelegate += (string name, int age) =>
{
    Console.WriteLine("Anonymous method is starting to work");
    return age + 2;
};

// execution of some method whith delegate as last parameter
objProgram.PrintBaseInfo("example", -2, objDelegate);

But why I can pass methods WITHOUT creating a delegate for them?但是为什么我可以在不为它们创建委托的情况下传递方法?

objProgram.PrintBaseInfo("Alexandr", 23, anotherClass.MyMethod);

In the example above i'm just passing method of some class (not delegate).在上面的例子中,我只是传递一些 class 的方法(不是委托)。 My assumption is that compiler creates delegate for it and initializes it with this method, but i'm not sure.我的假设是编译器为其创建委托并使用此方法对其进行初始化,但我不确定。

PS Just to remove misunderstanding of question, here is definiton of PrintBaseInfo: PS 只是为了消除对问题的误解,这里是 PrintBaseInfo 的定义:

public void PrintBaseInfo(string name, int age, MyDelegate InnerFunc){some code}

You are right, compiler will create delegate for you.你是对的,编译器会为你创建委托。

TryRoslyn 尝试罗斯林

using System;

public class SomeClass
{
    public void TakesAction(Action action)
    {
    }

    public void CallsTakesAction()
    {
        TakesAction(MethodName);
    }

    public static void MethodName()
    {
    }
}

Is compiled to:编译为:

using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
public class SomeClass
{
    public void TakesAction(Action action)
    {
    }

    public void CallsTakesAction()
    {
        TakesAction(new Action(MethodName));
    }

    public static void MethodName()
    {
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM