为什么能代表可以互换使用类方法和静态函数? [英] Why can delegates can be used interchangeably for Class methods and Static functions?

查看:98
本文介绍了为什么能代表可以互换使用类方法和静态函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用了代表多年,并没有真正给他们多想。
,但我最近通过假设代表引用一个类的方法时,包括了在签名本引用了我的脸鸡蛋。
下面的例子说明了我的理解的差距。

I've been using delegates for many years, and haven't really given them much thought. But I recently got egg on my face by assuming that delegates included a this reference in the signature when referencing a class method. The below example illustrates the gap in my understanding.

public class SomeClass
{
    public SomeClass(int someProperty)
    {
        SomeProperty = someProperty;
    }

    public int SomeProperty
    { 
        get; 
        set; 
    }

    // Throw in a Member field into the mix
    public int ClassAdd(int x, int y)
    {
        return x + y + SomeProperty;
    }
}

public static class SomeStaticClass
{
    public static int StaticAdd(int x, int y)
    {
        return x + y;
    }
}



为什么我可以添加静态和实例?用户

Why is it that I can add both static and instance subscribers?

    delegate int addDelegate(int x, int y);

    class TestClass
    {
        delegate int addDelegate(int x, int y);

        private void useDelegates()
        {
            addDelegate algorithm;
            algorithm = SomeStaticClass.StaticAdd;
            algorithm += new SomeClass(3).ClassAdd;

            int answer = algorithm(5, 10);
        }
    }



什么的实际去上? ;)

推荐答案

如果你创建一个委托指的是一个实例方法,它会捕捉这个(或相关参考)领域来头的 目标 委托的财产。如果你创建一个委托指的是一个静态方法,在目标将是空的。从逻辑上没有必要有,如果您使用的是静态方法的一个实例。

If you create a delegate referring to an instance method, it will capture this (or the relevant reference) in the field backing the Target property of the delegate. If you create a delegate referring to a static method, the Target will be null. Logically there's no need to have an instance if you're using a static method.

作为一个附加的并发症,可以拍摄的扩展的方法如如果他们在扩展类型实例方法:

As one added complications, you can capture extension methods as if they were instance methods on the extended type:

static class Extensions
{
    public static void Foo(this string x)
    {
        Console.WriteLine("Calling Foo on " + x);
    }
}

class Test
{
    static void Main()
    {
        Action action = "text".Foo;
        Console.WriteLine(action.Target); // Prints "text"
    }
}



至于为什么的你可以做到这一切:因为它是有用的,而且也没有理由的的让你做到这一点:)

As for why you can do all of this: because it's useful, and there's no reason not to allow you to do it :)

这篇关于为什么能代表可以互换使用类方法和静态函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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