您如何將串列分配給通用串列,因為它們不是同一型別。
如果我有一個通用串列:
List<T> myList = new List<T>();
我還有另一個清單
List<OtherType> otherList = new List<OtherType>();
在我填寫otherList值之后。有哪些方法可以將 otherList 分配給通用串列?最好不使用 foreach。
uj5u.com熱心網友回復:
如果它們是相同的型別,您可以進行基本的型別轉換
if(typeof(T) == typeof(OtherType))
myList = otherList as List<T>;
但這沒有任何意義,所以我想你需要某種轉換,問題是我們需要指定 T 可以從你的基類中分配
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 可以轉換為的任何其他類呼叫上述代碼,則上述代碼將起作用。或者,您可能想要一組預定義型別的具體轉換方法,這有點駭人聽聞,但您可以做這樣的事情
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}");
}
}
泛型型別和具體類之間關系的一些背景關系會有所幫助
編輯:一些忽略您的實際問題的建議。最有可能的是,您想創建一個介面并回傳該介面的串列(我假設這將更接近您的用例)。或者,只需更改簽名以回傳 List< object> - 然后你可以做
return otherList.ToList<object>();
uj5u.com熱心網友回復:
List<T>是不變的,因此您只能分配相同型別的串列。您最接近的方法是創建一個包含相同專案的新串列。
List<T> list = otherList.Select( x => (T)x ).ToList();
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/449274.html
