有没有什么办法可以做到我想要的?而在抽象基类中使用具体实现类型
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()'约束) – haim770
您是否尝试过'out TExists existingElement '和'TExists temp;'? –
@FabioLuz:'TExists'是包含存在检查数据的对象的基类型,而不是应该返回的对象的类型 - – KingKerosin