为什么不是演员工作? [英] Why does as instead of a cast work?

查看:119
本文介绍了为什么不是演员工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类,第一个类引用第二个类。我的问题是,为什么在第二个类中,行 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; //不行的
}
}


解决方案

这是因为作为是安全的转换,即如果类型不能被转换,它不会引发异常或编译器错误。它将简单地返回 null 。在使用作为之后, c1.container 应该是 null / p>

在您的代码中,您可能试图使用变体泛型。查看 MSDN上的此链接,以帮助您实现您尝试的目标做。您将必须使用接口,并且无法使协变和逆变的类型参数。


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
    }
}

解决方案

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.

这篇关于为什么不是演员工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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