[英]Return IEnumerable<IMyInterface> from List<MyInterfaceClass>
EDIT : This question would be invalid in .NET 4 since it actually works as desired. 编辑 :此问题在.NET 4中将无效,因为它实际上按预期工作。
I have a Data class that must implement an interface like this: 我有一个数据类,必须实现这样的接口:
public interface IData
{
IEnumberable<IOther> OtherList { get; }
IOther AddOther();
void RemoveOtherData(IOther data);
}
But I am stuck with declaring the actual member in Data 但是我坚持声明数据中的实际成员
public class Data : IData
{
// desired, always return the same reference
public IEnumberable<IOther> OtherList { get { return _mOtherList } }
// Non persistent reference not desirable.
public IEnumerable<IOther> OtherList { get { return _mOtherList.Select(x => x as IOther); } }
List<IOther> _mOtherList = new List<Other>(); // error, type mismatch
List<Other> _mOtherList = new List<Other>(); // error, property return type mismatch
IEnumerable<IOther> _mOtherList = new List<Other>(); // ok, but cannot use List methods without casting.
}
What would be the best solution in this case? 在这种情况下最好的解决方案是什么?
public class Data : IData
{
public IEnumerable<IOther> OtherList { get; private set; }
List<Other> _mOtherList = new List<Other>();
public Data()
{
OtherList=mOtherList.Cast<IOther>();
}
}
On .net 4 IEnumerable<out T>
is co-variant. 在.net 4上,
IEnumerable<out T>
是协变的。 ie a class that implements IEnumerable<Other>
automatically implements IEnumerable<IOther>
too. 即,实现
IEnumerable<Other>
的类IEnumerable<IOther>
自动实现IEnumerable<IOther>
。 So could also simply write: 所以也可以简单地写:
public class Data : IData
{
public IEnumerable<IOther> OtherList { get{return mOtherList;} }
List<Other> _mOtherList = new List<Other>();
}
But I'd avoid that, since it breaks encapsulation and allows outsiders to modify your list. 但我会避免这种情况,因为它会破坏封装并允许外部人员修改您的列表。
((List<Other>)MyData.OtherList).Add(...);
Other class must implement IOther interface and you don't need to cast. 其他类必须实现IOther接口,并且不需要强制转换。
When you declare _mOtherList, it's IEnumerable, so you can't use list methods. 声明_mOtherList时,它是IEnumerable,因此您不能使用列表方法。 Declare it as a list.
将其声明为列表。
public class Data : IData
{
List<IOther> _mOtherList = new List<Other>();
public IEnumberable<IOther> OtherList { get { return _mOtherList } }
IOther AddOther()
{
return null;
}
void RemoveOtherData(IOther data){}
}
Your Other class: 您的其他班级:
class Other : IOther
{
//some members
}
As IEnumerable is covariant this is fine: 由于IEnumerable是协变的,所以很好:
public interface IInterface{}
public class ClassA : IInterface{}
public class ClassB
{
private readonly List<ClassA> _classAs;
public IEnumerable<IInterface> Data{ get { return _classAs; } }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.