[英]object[] to List<Interface> returns null
如果我有一個看起來像這樣的物體:
class Person : IProxy
{
// Properties
}
我有一個返回的方法object
實際上是一個List<Person>
:
object GetList()
{
List<Person> people = new List<Person>();
person.Add(new Person());
person.Add(new Person());
return people;
}
為什么以下代碼導致null?
var obj = GetList() as List<IProxy>;
但是下面的代碼返回一個List:
var obj = GetList() as List<Person>;
在Visual Studio的Watch面板中,我的類型報告為:
object {System.Collections.Generic.List<Person>}
List<Person>
和List<IProxy>
是兩種不同的類型,因此將一個轉換為另一個可能會產生null。
GetList().OfType<IProxy>()
會做你想做的。 你也可以使用
GetList().Cast<IProxy>()
我個人更喜歡OfType,因為當集合包含異構類型時它不會拋出異常
協方差和反差異常見問題可能會回答您的更多問題。
因為List<People>
是List<IProxy>
的不同類型。 想象一下,你有class Cat : IProxy
。 如果您可以將List<People>
為List<IProxy>
那么您可以添加一個Cat
,我認為您不需要它。 缺少的是這里的通用逆轉,例如,在java中你可以合法地將你的列表轉換為List<? extends IProxy>
List<? extends IProxy>
,這將允許您從列表中讀取IProxy
對象,但不向其寫入任何內容。
為什么GetList()
object
的返回類型? 指定List<Person>
或IList<Person>
會更有意義。 這樣,調用方法后就不必進行強制轉換。
如果你想從你的方法中獲得List<IProxy>
,你會這樣做:
List<IProxy> GetList()
{
List<IProxy> people = new List<IProxy>();
people.Add(new Person());
people.Add(new Person());
return people;
}
然后
var obj = GetList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.