限制MyClass转换错误的c#扩展方法
我有一个对MyClass有限制的扩展方法。我想做的是:限制MyClass转换错误的c#扩展方法,c#,type-conversion,extension-methods,C#,Type Conversion,Extension Methods,我有一个对MyClass有限制的扩展方法。我想做的是: public static void GetXmlDocValues<T>(this List<T> collection, XmlDocument xmlDoc) where T : MyClass { collection.Clear(); foreach (XmlNode item in xmlDoc.ChildNodes) { ((List<MyClass
public static void GetXmlDocValues<T>(this List<T> collection, XmlDocument xmlDoc) where T : MyClass
{
collection.Clear();
foreach (XmlNode item in xmlDoc.ChildNodes)
{
((List<MyClass>)collection).Add(new MyClass(item));
}
}
publicstaticvoid GetXmlDocValues(这个列表集合,xmldocumentxmldoc),其中T:MyClass
{
collection.Clear();
foreach(xmlDoc.ChildNodes中的XmlNode项)
{
((列表)集合)。添加(新MyClass(项目));
}
}
然后我得到了一个错误:
无法将类型“System.Collections.Generic.List
”转换为
“System.Collections.Generic.List
”。
此处:((列表)集合)
有可能做那件事吗?或者它在任何情况下都会出错。看起来您确实希望您的方法如下所示:
public static void GetXmlDocValues(this List<MyClass> collection, XmlDocument xmlDoc)
{
collection.Clear();
foreach (XmlNode item in xmlDoc.ChildNodes)
{
collection.Add(new MyClass(item));
}
}
publicstaticvoid GetXmlDocValues(此列表集合,XmlDocument xmlDoc)
{
collection.Clear();
foreach(xmlDoc.ChildNodes中的XmlNode项)
{
集合。添加(新MyClass(项目));
}
}
如果您只想使用
MyClass
是的,那么不需要通用方法。为什么我们需要“哪里”限制?仅用于覆盖?@Novikov:其中
来自泛型的使用。没有泛型,不需要where
。一个Get
方法返回void
!!!并修改其对象!!!并删除!!!如何命名它重新加载
?(“从XML”将由参数类型暗示。)