问题描述
我一直在使用代表多年,并没有真正给予他们很多的想法。但是我最近在我的脸上收到了蛋,假设委托人在引用类方法时在签名中包含一个
这个
引用。 下面的例子说明了我的理解差距。
public class SomeClass
{
public SomeClass(int someProperty)
{
SomeProperty = someProperty;
}
public int SomeProperty
{
get;
设置;
}
//在会员字段中投入混合
public int ClassAdd(int x,int y)
{
return x + y + SomeProperty;
}
}
public static class SomeStaticClass
{
public static int StaticAdd(int x,int y)
{
返回x + y;
}
}
为什么我可以添加静态和实例订阅者?
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);
}
}
上? ;)
如果创建一个引用一个实例方法的委托,它将捕获 code>(或相关参考)在后台支持属性的委托。如果创建一个引用静态方法的委托,则
Target
将为null。逻辑上,如果您使用静态方法,则无需实例。
由于增加了一些并发症,您可以将扩展名方法捕获为如果它们是扩展类型的实例方法:
static class Extensions
{
public static void Foo (这个字符串x)
{
Console.WriteLine(Calling Foo on+ x);
}
}
class Test
{
static void Main()
{
Action action =text。 oo
Console.WriteLine(action.Target); //打印text
}
}
至于为什么可以执行以下所有操作:因为它很有用,并且没有理由不允许您执行此操作:
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);
}
}
What is actually going on? ;)
解决方案 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 :)
这篇关于为什么代表可以互换使用Class方法和静态函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!