开发者

OpCodes.Castclass. Is it necessary?

开发者 https://www.devze.com 2023-03-10 19:11 出处:网络
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

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消