示例:
public class MyList<T> : List<T> {
public MyList(List<T> list) {
this = list; // this is basically what I want, but doesn't work
base = list; // this also doesn't work
}
}
有什么解决办法吗?或者我想要实现的目标只是一个坏主意?
动机:我想向 List 对象添加自定义函数。
如果您使用.Net Framework 3.5,在列表上定义扩展方法不是更容易吗?类似...
public static class MyListExtensionClass
{
public static void MyList<T>(this List<T> list)
{
// Your stuff
}
}
你能不做吗:
public MyList(List<T> list) : base(list)
或者,你不能在 List 对象上使用扩展方法吗?
public MyList(列表列表):base(列表)
这将调用基类的以下构造函数(在本例中为 List):
public List(IEnumerable<T> collection);
public class MyList<T> : List<T>
{
public MyList(List<T> list)
{
AddRange(list);
}
}
这是我的方法:
// Function which instantiates a derived class D for a provided base class B,
// then assigns all class properties that exist in instance B to derived instance D
public static D DownCast<B, D>(this B baseClass) where D : new()
{
var newDerived = new D();
var properties = baseClass.GetType().GetProperties();
foreach (var prop in properties)
{
var derivedPropValue = prop.GetValue(baseClass, null);
var baseProp = baseClass.GetType().GetProperty(prop.Name);
var hasProperty = baseProp != null;
if (hasProperty)
{
baseProp.SetValue(newDerived, derivedPropValue, null);
}
}
return newDerived;
}