我有一个集合类,像这样:C#的隐式转换
public class SomeDataCollection : List<ISomeData>
{
// some method ...
}
,但我不能做到这一点:
SomeDataCollection someDatas = new List<ISomeData>();
无法隐含转换型
List<ISomeData>
到SomeDataCollection
。一个显式转换存在(是否缺少强制转换?)
,所以我尝试创建内部SomeDataCollection
集合类隐式coverter:
public static implicit operator SomeDataCollection(List<ISomeData> l)
{
var someDatas = new SomeDataCollection();
someDatas.AddRange(l);
return someDatas;
}
,但它说,我不能创造这样的转换器:
SomeDataCollection.implicit operator SomeDataCollection(List<ISomeData>)
:用户定义的转换或从基类不允许
当我投它是这样的:
SomeDataCollection someDatas = (SomeDataCollection)new List<ISomeData>();
它抛出一个错误,说:
System.InvalidCastException:无法转换
List<ISomeData>
类型的对象类型SomeDataCollection
。
我怎样才能做到这一点:
SomeDataCollection someDatas = new List<ISomeData>();
没有得到一个错误?请帮忙。提前致谢。
可能dupplicate:http://stackoverflow.com/questions/3401084/user-defined-conversion-operator-from-base-class – albertjan