OpCodes.Castclass。有必要吗? [英] OpCodes.Castclass. Is it necessary?

查看:91
本文介绍了OpCodes.Castclass。有必要吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您准备在堆栈顶部引用(B)的实例时,有必要发出OpCode.CastClass(typeof(A)),其中B是从A派生的类,其中B是类。类型为A的参数?

Is it necessary to emit OpCode.CastClass(typeof(A)) when you having a reference to instance of (B) on top of stack, where B is class, derived from A, when preparing for a call to method with argument of type A?

加法:

interface IFoo
{
    void IFoo();

}

public class A:IFoo
{
    public void IFoo()
    {

    }
}
public class B:A,IFoo
{
    new public void IFoo()
    {

    }
}

var b = new B();

(b as IFoo).Foo();
((b as A) as IFoo).Foo();


推荐答案

我猜你有这样的东西:

class A
{
    public void Foo() { }
}

class B : A
{
}

B b = new B();
b.Foo();

B b = new B();
((A)b).Foo();

两者都可以。但是强制转换不是必需的,因为 B 继承了 A 的所有成员。

Both work. But the cast is not necessary, because B inherits all members from A.

这篇关于OpCodes.Castclass。有必要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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