我正在尝试从接口继承两个不同的模型。这些模型应该作为列表或集合传递给方法。现在我收到此错误消息:
The type 'InheritanceTest.FooModel' cannot be used as type parameter 'T' in the generic type or method 'InheritanceTest.Service.DoSomethingWith<T>(System.Collections.Generic.IEnumerable<T>)'. There is no implicit reference conversion from 'InheritanceTest.FooModel' to 'InheritanceTest.IModel<InheritanceTest.IModelItem>'. C:\Work\InheritanceTest\InheritanceTest\Program.cs 14 13 InheritanceTest
Run Code Online (Sandbox Code Playgroud)
有人可以解释一下我做错了什么吗?:D
演示代码:
interface IModel<T> where T : IModelItem
{
string Name { get; set; }
IEnumerable<T> Items { get; set; }
}
interface IModelItem
{
string Name { get; set; }
}
class FooModel : IModel<FooModelItem>
{
public FooModel()
{
Items = new List<FooModelItem>();
}
public string Name …Run Code Online (Sandbox Code Playgroud) interface IFolderOrItem<TFolderOrItem> where TFolderOrItem : FolderOrItem {}
abstract class FolderOrItem {}
class Folder : FolderOrItem {}
abstract class Item : FolderOrItem {}
class Document : Item {}
Run Code Online (Sandbox Code Playgroud)
现在我想这样做:
class Something
{
IFolderItemOrItem<Item> SelectedItem { get; set; }
void SomeMagicMethod()
{
this.SelectedItem = (IFolderOrItem<Item>)GetMagicDocument();
// bad bad bad ... ??
}
IFolderOrItem<Document> GetMagicDocument()
{
return someMagicDocument; // which is of type IFolderOrItem<Document>
}
}
Run Code Online (Sandbox Code Playgroud)
有没有可能让这个工作?