Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Generics 泛型适用于sefty类型?派生类型呢?_Generics_C# 3.0 - Fatal编程技术网

Generics 泛型适用于sefty类型?派生类型呢?

Generics 泛型适用于sefty类型?派生类型呢?,generics,c#-3.0,Generics,C# 3.0,我正在使用.NET3.5框架。 下面是我的代码 class Base {} class Derived : Base {} class Program { static Main() { IList<Base> base_col = new List<Base>(); base_col.Add(new Derived()); // Do you think this line code is good? } } 类基类{} 派生类:基{} 班

我正在使用.NET3.5框架。 下面是我的代码

class Base {}

class Derived : Base {}

class Program {
  static Main() {
    IList<Base> base_col = new List<Base>();
    base_col.Add(new Derived()); // Do you think this line code is good?
  }
}
类基类{}
派生类:基{}
班级计划{
静态Main(){
IList base_col=新列表();
base_col.Add(new-Derived());//您认为这行代码好吗?
}
}
你认为泛型是进行类型检查的好方法吗

我会先走一步

static Main() { 
  IList<Derived> base_col = new List<Derived>(); 
  Process(base_col); // error. 
} 
static Process(IEnumarable<Base> baseCollection) { } 
static Main(){
IList base_col=新列表();
进程(基本列);//错误。
} 
静态进程(IEnumarable baseCollection){}

为什么代码在这里断开?

因为
派生的
也是一个
,所以显示的代码没有问题,而且与泛型没有什么关系

关于您的编辑:您提供的代码在.NET4中确实有效,
IEnumerable
接口是反向的。以前的版本没有使用此功能(自V2以来,CLR中显然一直支持接口中的协变/逆变,但直到.NET Framework的V4,才有语言使用此功能发出代码)

对于这种特定情况,您可以安全地使用
Cast
LINQ功能,不过:

static Main() { 
  IList<Derived> base_col = new List<Derived>(); 
  Process(base_col.Cast<Base>());
} 
static Main(){
IList base_col=新列表();
过程(基本列Cast());
} 

如果您认为这很有趣,请等待,直到您尝试将IList传递给接受IListI的方法,该方法完全同意您的意见。。。请在上面找到我的更新代码。