随笔- 7  文章- 0  评论- 16 

标题纯属忽悠,不过是玩'this'的小把戏

C#3.0的扩展方法(静态类的静态方法):

public static class A
{
    public static int Add(this int i, int j)
    {
        return i + j;
    }
}

class tst
{
    static void Main()
    {
        Console.WriteLine(1.Add(3));
        Console.Read();
    }

}

 1.Add(3)其实就是A.Add(1,3)

俺弄得是this把戏,不过丑陋的很,仅供娱乐

一个非静态类: AgeManager,里面两个实例方法GetAge,SetAge

kkk里面的代码翻译成C#,多像:

Cat c = new Cat();

c.SetAge(11);

Console.Write(c.GetAge())

也可以:

Dog d = new Dog();

d.SetAge(6);

d.GetAge();

要再有个Pig( 只能有一个int32字段)

也能‘扩展‘一下

 

Cat Dog..有且只有一个int32字段

如下:

.assembly lee {}

.class private auto ansi zzz extends [mscorlib]System.Object
{
.method public  hidebysig static void kkk() il managed
{
.entrypoint
newobj instance void Cat::.ctor();
dup
ldc.i4 11
call instance void  AgeManager::SetAge(int32)
call instance int32  AgeManager::GetAge()
call void [mscorlib]System.Console::Write(int32)
ret
}
}

.class AgeManager
{
.method public hidebysig instance int32 GetAge() il managed
{
ldarga 0
ldobj int32
ldc.i4 4
add
ldobj int32
ret
}
.method public hidebysig instance void SetAge(int32) il managed
{
ldarga 0
ldobj int32
ldc.i4 4
add
ldarg.1
stobj int32
ret
}
.method public hidebysig specialname rtspecialname instance void .ctor()
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
.class Cat{
.field private int32 age
.method public hidebysig specialname rtspecialname instance void .ctor()
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}}
.class Dog{
.field private int32 age
.method public hidebysig specialname rtspecialname instance void .ctor()
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}}
其实就是把对象当this传给实例方法了,再按地址操作改了实例对应的age字段
 

 posted on 2008-09-27 18:31 红泥 阅读(...) 评论(...) 编辑 收藏