Why does as instead of a cast work? [duplicate]

Deadly 提交于 2019-12-13 17:23:51

问题


I have two classes, where the first class references the second class. My question is, why in the second class, the line cl.container = this as ClassContainer<MyClass>; does work and the explicit cast cl.container = (ClassContainer<MyClass>)this; does not.

class MyClass
{
    public ClassContainer<MyClass> container { get; set; }
}

second class:

class ClassContainer<T> where T : MyClass
{
    public ClassContainer()
    {
        MyClass cl = new MyClass();
        cl.container = this as ClassContainer<MyClass>; // works
        cl.container = (ClassContainer<MyClass>)this;   // does not work
    }
}

回答1:


This is because as is a safe cast, i.e. it will not raise an exception or a compiler error if the type can not be casted. It will simply return null. c1.container should be null after using as.

From your code, you may be trying to use variant generics. Check out this link at MSDN to help achieve what you were trying to do. You'll have to use interfaces though, and cannot make a type parameter both covariant and contravariant.



来源:https://stackoverflow.com/questions/42084389/why-does-as-instead-of-a-cast-work

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