在泛型类中隐藏非泛型基类属性或方法的标准模式是什么?
我有 2 个解决方案,实际上是做相同但不同的方法。解决方案一使用更多内存,因为基类和派生类引用相同的对象,而解决方案二由于强制转换而更慢。(或者我错了?)
基类:
public class MyDataBase {}
public class MyDataDerived : MyDataBase {}
public class BaseFoo
{
private readonly MyDataBase _data;
public MyDataBase Data { get { return _data; } }
public BaseFoo(MyDataBase data) {
_data = data;
}
}
解决方案1:
public class GenericFooWithHiding<T> : BaseFoo where T : MyDataBase
{
private readonly T _data;
public GenericFooWithHiding(T data) : base(data) { _data = data; }
public new T Data { get { return _data; } }
}
解决方案2:
public class GenericFooWithCasting<T> : BaseFoo where T : MyDataBase
{
public GenericFooWithCasting(T data) : base(data) {}
public new T Data { get { return base.Data as T; } }
}