分配类型为T的数据成员字段/属性变量

时间:2017-06-21 17:29:16

标签: c#

为什么赋值语句

_t = new Y();

导致以下编译错误?

  

无法将类型'Y'隐式转换为'T'。存在显式转换(您是否错过了演员?)

public class X { }
public class Y { }
public class A<T> { }    
public class B<T> : A<X> where T : Y, new()
{
    private T _t;

    public B()
    {
        _t = new T();
        _t = new Y();  //compiler error
    }
}

1 个答案:

答案 0 :(得分:0)

rowSelected: number; isRowSelected(i: number) { return i == this.rowSelected; } selectRow(i: number) { this.rowSelected = i; } 是显式转化。当且仅当T x = (T)new Y()实际为T时,它才会在运行时工作。如果YT的任何子类,它将抛出异常。因此,不要使用泛型类型参数 - 如果您的类要求Y实际上始终为T,则它不应该是通用的。它应该只使用Y

Y是一个类型参数。只有一个允许值的参数不是参数。这是一个常数。

T

public class Y { public int YStuff; } public class YSubclass : Y { public int YSubclassStuff; } public class Generic<T> where T : Y, new() { public static void Test() { // NEVER DO THIS, EVER T x = (T)new Y(); } } 约束表示您用于where Y的任何类型必须是TY的子类。它可以是Y的子类,增加了十个其他的东西。如果YT,则YSubclass 不是那个。这只是那件事的一部分。

你不能这样做:

Y

Y y = new Y(); var x = y.YSubclassStuff; 没有该字段。您不能假装YY。它不是。这不仅仅是“坏形式”或“捷径”的东西;它不可能

...

YSubclass

您需要使用虚拟方法或接口解决问题。这些是从这里到达那里的安全,可接受的方式。

您可以要求T实现给定的接口,例如:

public static void Main()
{
    //  OK
    Generic<Y>.Test();

    //  System.InvalidCastException: 'Unable to cast object of type 
    //  'WpfApp1.Y' to type 'WpfApp1.YSubclass'.'
    //  And that's why what I did in Test() is a really, really bad idea
    //  and you should never do it. 
    Generic<YSubclass>.Test();
}

现在您可以创建public interface Z { void F(); } public class Generic<T> where T : Y, Z, new() ,无论它是什么,并保证任何T都有T