C#泛型抽象类从抽象泛型类继承 [英] c# Abstract Generic Class inheriting from Abstract Generic Class
本文介绍了C#泛型抽象类从抽象泛型类继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图创建一个抽象泛型类从另一个抽象泛型类继承。
I'm trying to create an abstract generic class which inherits from another abstract generic class.
下面是我迄今为止
public abstract class BaseClass {
public long Id { get; private set; }
public BaseClass(long id) {
this.Id = id;
}
}
public abstract class BaseClass<T> : BaseClass where T : BaseClass {
protected BaseClass(long id)
: base(id) {
}
public static T Get(long id) {
T item;
return TryGet(id, out item) ? item : default(T);
}
public static bool TryGet(long id, out T item) {
item = null; // This is where I call the cache but for this example I've removed so it will compile
if (item != null) { return true; }
else {
// Call TryGetFallback method
return false;
}
}
protected abstract T TryGetFallback(long id);
}
public abstract class DerivedClass : BaseClass<DerivedClass> {
public String Name { get; private set; }
public DerivedClass(long id, String name)
: base(id) {
this.Name = name;
}
}
public class DerivedDerivedClass : DerivedClass {
protected override DerivedDerivedClass TryGetFallback(long id) {
// Handle the try get fallback
}
}
在DerivedDerivedClass的TryGetFallback方法将导致编译。误差
The TryGetFallback method on the DerivedDerivedClass causes a compiler error.
推荐答案
首先,你需要修复你的的BaseClass< T>
。实施没有递归类型约束
First you need to fix your BaseClass<T>
implementation to not have a recursive type constraint.
public abstract class BaseClass<T> : BaseClass where T : new() {
//snip
}
然后你就可以在你的派生类中使用它,比如我会使其使用 INT
泛型类型参数:
public abstract class DerivedClass : BaseClass<int> {
//snip
}
现在,如果你编译它会警告您'DerivedDerivedClass不实现继承的抽象成员的BaseClass< INT> .TryGetFallback(长)
这篇关于C#泛型抽象类从抽象泛型类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文