OpCodes.Castclass. Is it necessary?

旧时模样 提交于 2019-12-13 15:03:07

问题


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?

Addition:

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();

回答1:


I guess you have something like this:

class A
{
    public void Foo() { }
}

class B : A
{
}

and need to decide between:

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

and

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

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



来源:https://stackoverflow.com/questions/6265453/opcodes-castclass-is-it-necessary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!