相关疑难解决方法(0)

类型不能用作泛型类型或方法中的类型参数“T” - 为什么?

我正在尝试从接口继承两个不同的模型。这些模型应该作为列表或集合传递给方法。现在我收到此错误消息:

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)

c# inheritance interface

8
推荐指数
1
解决办法
4万
查看次数

为什么这个演员不可能?

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)

有没有可能让这个工作?

c# oop generics

4
推荐指数
2
解决办法
3515
查看次数

标签 统计

c# ×2

generics ×1

inheritance ×1

interface ×1

oop ×1