为什么不是演员工作? [英] Why does as instead of a cast work?
问题描述
我有两个类,第一个类引用第二个类。我的问题是,为什么在第二个类中,行 cl.container = this作为ClassContainer< MyClass>;
确实有效并且显式强制转换 cl。 container =(ClassContainer< MyClass>)this;
不会。
class MyClass
{
public ClassContainer< MyClass>容器{get;组; }
}
第二课程:
class ClassContainer< T>其中T:MyClass
{
public ClassContainer()
{
MyClass cl = new MyClass();
cl.container = this作为ClassContainer< MyClass>; //作品
cl.container =(ClassContainer< MyClass>)this; //不行的
}
}
这是因为 在您的代码中,您可能试图使用变体泛型。查看 MSDN上的此链接,以帮助您实现您尝试的目标做。您将必须使用接口,并且无法使协变和逆变的类型参数。 I have two classes, where the first class references the second class. My question is, why in the second class, the line second class:
This is because 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. 这篇关于为什么不是演员工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!作为
是安全的转换,即如果类型不能被转换,它不会引发异常或编译器错误。它将简单地返回 null
。在使用作为
之后, null
/ p>
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; }
}
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
}
}
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
.