将列表分配给通用列表

Assign List to a generic list

您如何将列表分配给通用列表,因为它们不是同一类型。

如果我有一个通用列表:

List<T> myList = new List<T>();

我还有另一个列表

List<OtherType> otherList = new List<OtherType>();

在我用值填充 otherList 之后。我可以通过哪些方式将 otherList 分配给通用列表?最好不使用 foreach。

List<T> 是不变的,所以你只能分配相同类型的列表。最接近的是创建一个包含相同项目的新列表。

List<T> list = otherList.Select( x => (T)x ).ToList();

如果它们是同一类型,您可以进行基本类型转换

if(typeof(T) == typeof(OtherType))
    myList = otherList as List<T>;

但这没有任何意义,所以我想你需要某种转换,问题是我们需要指定 T 是可从你的基础分配的 class

public static class StaticFoo
{
    public static List<T> Foo<T>() where T : class
    {
        List<MyOtherClass> returnList = new List<MyOtherClass>() { new MyOtherClass() };
        if(typeof(T).IsAssignableFrom(typeof(MyOtherClass)))
            return returnList.Select(x => x as T).ToList();
        throw new Exception($"Cannot convert {typeof(T)} to MyOtherClass");
    }
}
public class MyClass { }
public class MyOtherClass : MyClass { }

如果您使用 T = MyClass 或任何其他可以转换为 myOtherClass 的 class 来调用上面的代码,则上述代码将起作用。或者,您可能需要针对一组预定义类型的具体转换方法,这有点老套,但您可以这样做

public static class StaticFoo
{
    public static List<T> Foo<T>() where T : class
    {
        List<MyOtherClass> returnList = new List<MyOtherClass>() { new MyOtherClass() };
        return returnList.Select(x => x.Convert(typeof(T)) as T).ToList();
    }
}
public class MyOtherClass {
    public object Convert(Type type) {
        if (type == typeof(string)) //more if statements for more types
            return this.ToString(); //just an example
        throw new NotImplementedException($"No cast available for type {type}");
    }

}

关于泛型类型和具体 class 之间关系的一些上下文会有所帮助

编辑: 一些忽略您实际问题的建议。最有可能的是,您想创建一个接口和 return 该接口的列表(我假设这将更接近您的用例)。或者只需将签名更改为 return List< object> - 然后你可以做

return otherList.ToList<object>();