Ian*_*cer 5 generics abstract-class
您是否认为创建一个抽象泛型类是一种可接受或不好的做法,该类将类型参数作为一个派生自己的类?
这允许抽象泛型类操作派生类的实例,特别是在必要时创建派生类的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;
}
}
Run Code Online (Sandbox Code Playgroud)
还有第二个问题:为什么这些隐式算子中的一个有效,而另一个没有?
例如
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;
Run Code Online (Sandbox Code Playgroud)
这有点主观,但我不太喜欢隐式转换。当您使用它们时,代码常常会产生误导,有时如果是由隐式强制转换引起的错误,则很难找到错误。如果你的课程只是为了使用它们而设计的,那么我不会以这种方式使用它。
为什么这些隐式运算符之一有效而另一个无效?
因为您定义了来自 的转换CoolClass<T, U>,但没有定义来自 的转换CoolInt。它们是不同的类型。如果您的 CoolInt 实现中有此方法,它将起作用:
public static implicit operator CoolInt(int val)
Run Code Online (Sandbox Code Playgroud)
关于泛型的使用:
如果您需要使用许多类创建复杂的继承层次结构(例如,引入新的抽象级别可能很棘手),那么泛型的这种使用会给您的体系结构带来限制。但这实际上取决于您的需要。我实际上在一个项目中使用了这种技术来避免代码重复。如果您要克服 new() 限制,您也可以将委托传递Func<U>给构造函数:)CoolClass