简体   繁体   English

C#泛型方法值

[英]C# generic method value

I need to write method, that returns children of generic class in List . 我需要编写方法,返回List中泛型类的子代。 I wrote something like this : 我写了这样的东西:

static List<Model<T>> Get<T>( string value ) where T : Model<T>
{
    switch( value )
    {
        case "ROLE":
        return GetRoles();
    }
    return new List<Model<T>>();
}

GetRoles() returns List<Role> , where Role : Model<Role> . GetRoles()返回List<Role> ,其中Role : Model<Role>
But visual studio tells me that it cannot convert List<Role> to List<Model<T>> . 但是visual studio告诉我它无法将List<Role>转换为List<Model<T>>

The error here is that List<Role> is not the same as List<Model<T>> even if Role is a Model<Role> 这里的错误是List<Role>List<Model<T>>即使RoleModel<Role>

Example, you have two classes: 例如,您有两个类:

public class Bar : Model<Foo>
{

}

public class Foo : Model<Foo>
{

}

and create a list: 并创建一个列表:

var fooList = new List<Foo>();

if you could cast it to List<Model<Foo>> : 如果你可以将它List<Model<Foo>>List<Model<Foo>>

var modelList = (List<Model<Foo>>) fooList ; // not possible

than you should be able to add new Bars to list: 比你应该能够添加新的条形列表:

modelList.Add(new Bar());

But that is still a list of Foo and it could have only Foo objects. 但这仍然是Foo的列表,它可能只有Foo对象。

As a solution you could try to cast your Role to Model: 作为解决方案,您可以尝试将角色转换为模型:

static List<Model<T>> Get<T>(string value)  where T:Model<T>
{
    switch (value)
    {
        case "ROLE":
            return GetRoles().Cast<Model<T>>().ToList();
            break;
    }
    return new List<Model<T>>();
}

The problem here is that List<T> is not covariant . 这里的问题是List<T>不是协变的 What that means is that if you were allowed to do this, the caller would think it had a List<Model<T>> but in fact would have a List<Role> - if you then tried adding an instance of another class derived from Model<T> to your list it would fail. 这意味着如果你被允许这样做,调用者会认为它有一个List<Model<T>>但实际上会有一个List<Role> - 如果你然后尝试添加一个派生自另一个类的实例Model<T>到你的列表它会失败。 C# won't let you do that. C#不会让你这样做。

Instead, you could explicitly convert your result to List<Model<T>> using: 相反,您可以使用以下方法将结果显式转换为List<Model<T>>

return new List<Model<T>>(GetRoles());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM