【发布时间】:2011-03-20 20:08:17
【问题描述】:
你认为创建一个抽象的泛型类是可以接受的还是不好的做法?
这允许抽象泛型类操作派生类的实例,特别是能够根据需要创建派生类的 new() 实例,并有助于避免在派生自它的具体类中重复代码.
如果“不好”,你更喜欢用什么替代方法来处理这种情况,你会如何构造下面的代码?
例如:-
// We pass both the wrapped class and the wrapping class as type parameters
// to the generic class allowing it to create instances of either as necessary.
public abstract class CoolClass<T, U>
where U : CoolClass<T, U>, new()
{
public T Value { get; private set; }
protected CoolClass() { }
public CoolClass(T value) { Value = value; }
public static implicit operator CoolClass<T, U>(T val)
{
// since we know the derived type and that its new(), we can
// new up an instance of it (which we couldn't do as an abstract class)
return new U() { Value = val};
}
public static implicit operator T(CoolClass<T, U> obj)
{
return obj.Value;
}
}
还有一个额外的问题:为什么这些隐式运算符中的一个有效而另一个无效?
例如
public class CoolInt : CoolClass<int, CoolInt>
{
public CoolInt() { }
public CoolInt(int val) (val) { }
}
// Why does this not work
CoolInt x = 5;
// when this works
CoolInt x2 = (CoolInt)5;
// and this works
int j = x;
【问题讨论】: