C#-铸造问题
当试图将定义自定义泛型的类强制转换为子类时,我得到一个错误。我做错了什么C#-铸造问题,c#,inheritance,casting,C#,Inheritance,Casting,当试图将定义自定义泛型的类强制转换为子类时,我得到一个错误。我做错了什么 using System.Collections.Generic; interface IStorageComponent { } abstract class CollectionManager<T> where T : IStorageComponent { } class Bar : IStorageComponent { } class Foo : CollectionManager<Ba
using System.Collections.Generic;
interface IStorageComponent { }
abstract class CollectionManager<T> where T : IStorageComponent { }
class Bar : IStorageComponent { }
class Foo : CollectionManager<Bar> { }
class Storage
{
static int Main(string[] args)
{
List<CollectionManager<IStorageComponent>> manager = new List<CollectionManager<IStorageComponent>>
{
new Foo() // <-- cannot convert from 'Foo' to 'CollectionManager<IStorageComponent>'
};
return 0;
}
}
使用System.Collections.Generic;
接口IStorageComponent{}
抽象类CollectionManager,其中T:IStorageComponent{}
类栏:IStorageComponent{}
类Foo:CollectionManager{}
类存储
{
静态int Main(字符串[]args)
{
列表管理器=新列表
{
new Foo()//一个Foo
不是一个CollectionManager
,就像一堆香蕉不是Collection
——你可以将一个苹果添加到集合中,但你不能将它添加到一堆香蕉中。。。(我们无法判断在您的情况下这是否真的是一个问题,因为CollectionManager
为空-但它有可能成为一个问题。C允许在适当的情况下为接口和委托指定通用变量,但不允许为类指定通用变量。)@JonSkeet,从您的博客或msdn中获得的任何有关该主题的阅读材料都会非常有用。@swalker:(IStorageComponent)new foo();
毫无意义,因为Foo
不是IStorageComponent
@Saravanan:从这里开始:@S.Walker:不,它与Intellisense无关。Foo
不能转换为AFoo
不是CollectionManager
,就像一堆香蕉不是收藏一样可以将一个苹果添加到集合中,但不能将其添加到一堆香蕉中。。。(我们无法判断在您的情况下这是否真的是一个问题,因为CollectionManager
为空-但它有可能成为一个问题。C允许在适当的情况下为接口和委托指定通用变量,但不允许为类指定通用变量。)@JonSkeet,从您的博客或msdn中获得的任何有关该主题的阅读材料都会非常有用。@swalker:(IStorageComponent)new foo();
毫无意义,因为Foo
不是IStorageComponent
@Saravanan:从这里开始:@S.Walker:不,它与Intellisense无关。Foo
不能转换为