mat*_*att 1 c# inheritance casting list
我有一个子类通用List的类.我这样做是为了实现一个我需要在这种列表上定期调用的toJSONString().所以我的班级是这样的:
public class Foos : List<Foo>
{
public string toJSONString()
{
//Do something here
}
}
Run Code Online (Sandbox Code Playgroud)
在另一个类我有一个方法这样做:
public class Bar
{
private Foos m_Foos = new m_Foos();
public Foos filterWith(Query p_query)
{
Foos newList = m_Foos.FindAll(
// Make a test through a delegate
});
return (newList);
}
}
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
错误CS0266:无法隐式转换类型
System.Collections.Generic.List<Foo>' toFoos'.存在显式转换(您是否缺少演员?)(CS0266)(Assembly-CSharp)
问题是m_Foos.FindAll(...)返回"List"而不是"Foos".显式转换不起作用,因为我有一个运行时错误.
我已阅读过这篇文章,但它似乎没有给出我的问题的适当解决方案: C# - 为什么我不能将List <MyObject>转换为继承自List <MyObject>的类?
不要只是为了添加这样的格式化方法而编写新类.请在列表中使用扩展方法:
public static class FooListExtensions
{
public static string toJSONString(this List<Foo> list)
{
return "...";
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以简单地说:
List<Foo> list = new List<Foo>();
var str = list.toJSONString();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
233 次 |
| 最近记录: |