【发布时间】:2015-11-12 12:04:39
【问题描述】:
有什么方法可以在这里做我想做的事吗?
基类定义如下:
public abstract class BaseClass<TExists>
where TExists : BaseExists
{
// needs to be overridden by child
protected abstract bool Exists(TExists existsData, out /*typeof(this)*/ existingElement); // <- how to have the concrete type here?
// static method to be invoked without any need of an instance
public static bool Exists(TExists existsData, out /*typeof(this)*/ existingElement)
{
var temp; // <-- how to set the type here?
// create a concrete instance
var instance = Activator.CreateInstance(???);
// call the concrete implementation
if(instance.Exists(existsData, out temp))
{
return true;
}
return false;
}
}
这里我们有一些具体的实现:
public class ChildClass : BaseClass<ChildClassExists>
{
protected override bool Exists(ChildClassExists exists, out ChildClass existingElement)
{
// do child-related things here
}
}
最后我想像这样使用它
ChildClass existing;
if(ChildClass.Exists(new ChildClassExists(), out existing)){
// do things here with the existing element of type 'ChildClass'
}
因为我这里不需要实例(这隐藏在 Exists 的基类实现中)。
更新 #1
正如在 InBetweens 第一个答案中一样,我现在有了:
public static bool Exists<T>(TExists existsModel, out T existingEntityModel)
where T : BaseClass<TExists>
{
var instance = Activator.CreateInstance<T>();
return instance.ExistsInternal(existsModel, out existingEntityModel);
}
protected abstract bool ExistsInternal<T>(TExists createModel, out T existingEntityModel)
where T : BaseClass<TExists>;
但这会在 ExistsInternal 方法的具体实现中引发错误
无法将源类型“ChildClass”转换为目标类型“T”
在覆盖中
protected override bool ExistsInternal<T>(ChildClassExists existsData, out T existingElement)
{
existingElement = new ChildClass(); // <-- here the error is thrown
return true;
}
【问题讨论】:
-
您必须添加另一个通用参数 (
TConcrete)。但总的来说,问题意味着糟糕的设计。此外,您可以使用new TConcrete()代替Activator.CreateInstance()(假设您可以添加new()约束) -
你试过
out TExists existingElement和TExists temp;吗? -
@FabioLuz:
TExists是包含存在检查数据的对象的基本类型,而不是应该返回的对象的类型- -
@haim770:为什么这个设计不好?我必须确保每个具体实现都有一个
Exists,但不需要创建实例来调用它。另一方面,什么是更好的解决方法? -
public static bool Exists<T>(TExists existsData, out T existingElement) where T: BaseClass<TExists>?
标签: c# generics inheritance abstract-class