相关疑难解决方法(0)

为什么这样做?从IL执行方法没有实例

我正在浏览你在C#或.NET中看到的最奇怪的角落什么?,这段代码让我思考了一下:

public class Program
{
    delegate void HelloDelegate(Strange bar);

    [STAThread()]
    public static void Main(string[] args)
    {
        Strange bar = null;
        var hello = new DynamicMethod("ThisIsNull",
            typeof(void), new[] { typeof(Strange) },
         typeof(Strange).Module);
        ILGenerator il = hello.GetILGenerator(256);
        il.Emit(OpCodes.Ldarg_0);
        var foo = typeof(Strange).GetMethod("Foo");
        il.Emit(OpCodes.Call, foo);
        il.Emit(OpCodes.Ret);
        var print = (HelloDelegate)hello.CreateDelegate(typeof(HelloDelegate));
        print(bar);
        Console.ReadLine();
    }

    internal sealed class Strange
    {
       public void Foo()
       {
           Console.WriteLine(this == null);
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

我确实理解代码的作用,但我不明白为什么它有效.是不是喜欢这样做null.Foo()?它就好像Foo()是静态的,而是被调用:Strange.Foo();.

你能告诉我我错过了什么吗?

.net c# il

9
推荐指数
1
解决办法
193
查看次数

虚函数C#

我理解虚函数是什么.但我没有得到的是他们如何在内部工作?

class Animal
{
    virtual string Eat()
    {
        return @"Eat undefined";
    }
}

class Human : Animal
{
    override string Eat()
    {
         return @"Eat like a Human";
    }
}


class Dog : Animal
{
    new string Eat()
    {
         return @"Eat like a Dog";
    }
}

static void Main()
{
    Animal _animal = new Human();
    Console.WriteLine(_animal.Eat());
    _animal = new Dog();
    Console.WriteLine(_animal.Eat());
}
Run Code Online (Sandbox Code Playgroud)

上面的输出给出:

Eat like a Human
Eat undefined
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,_animal是Animal类型,它引用了Human对象或Dog对象.这是什么意思?我理解在内存中_animal包含一个指向Human或Dog对象的地址.它如何决定调用哪个函数.在第一种情况下,我覆盖,因此调用了子的实现,但在第二种情况下,我使用new,因此调用了父实现.能告诉我发动机罩下发生了什么吗?

在此先感谢尼克

c# methods virtual

3
推荐指数
1
解决办法
1228
查看次数

标签 统计

c# ×2

.net ×1

il ×1

methods ×1

virtual ×1