您的位置:首页 > 其它

探究委托的如何实现非静态方法

2015-02-27 15:06 162 查看
在C#里面对于委托的如何加载非静态方法一直都很疑惑,自己对于非静态方法的认识来看,如果要安全的实现非静态方法必须引用实例里面的
字段,经过查阅资料,知道委托类里面有一个_target字段如果是委托的是静态方法值为零,如果委托是非静态为会自动寻找方法的实例,
说的很模糊,这个_target字段应该是一个object型,但是里面地址指向的什么。我先在程序上声明一个类有两个字段这两个字段一个为static
一个非static,有两个方法一个静态一个非静态,我在方法里面对类的方法进行操作,看看对实例有什么影响。

public delegate void testChangeDelegate();
public class testChange
{
public int notStaticInt;
public static int staticInt;
public struct textStruct
{
public int notStaticInt;
public static int staticInt;
}
public static void staticinWay()
{
textStruct tt = new textStruct();
Console.WriteLine("方法之前{0} {1}", staticInt,tt.notStaticInt);
staticInt += 1;
tt.notStaticInt += 1;
Console.WriteLine("方法之后{0} {1}", staticInt, tt.notStaticInt);

}
public void notStaticWay()
{
textStruct tt = new textStruct();
Console.WriteLine("方法之前{0} {1}", notStaticInt,tt.notStaticInt);
notStaticInt += 1;
tt.notStaticInt += 1;
Console.WriteLine("方法之后{0} {1}", notStaticInt, tt.notStaticInt);
}

}
}
testChange tt = new testChange();
testChangeDelegate ttc = new testChangeDelegate(tt.notStaticWay);
ttc += tt.notStaticWay;
ttc += testChange.staticinWay;
ttc += testChange.staticinWay;
ttc();
Console.WriteLine(tt.notStaticInt);
Console.WriteLine(testChange.staticInt);
Console.WriteLine(tt.tt.notStaticInt);
Console.WriteLine(testChange.textStruct.staticInt);


View Code
结果是

方法之前0 1
方法之后1 1
方法之前1 0
方法之后2 1
方法之前0 0
方法之后1 1
方法之前1 1
方法之后2 2
2
2
0
2


将类改成结构后
结果是

方法之前0 1
方法之后1 1
方法之前0 0
方法之后1 1
方法之前0 0
方法之后1 1
方法之前1 1
方法之后2 2
0
2
0
2


从结果看结构体tt的结果同上面结构体testChange相同,分析可知是浅层复制。

这样看来.net framework在后台给实例方法复制对象时采用的是浅层复制,而不是直接引用地址。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: