如何解决c# 在派生类中强制执行特定的方法签名抽象虚拟静态
我有一个 abstract class BaseClass
并希望强制所有 class Derived: BaseClass
都必须覆盖方法 foo
,从而产生一个非常具体的签名。问题如下:
- 继承自 BaseClass 的类必须自己实现
foo
(首选,仅当它们不是抽象时)[如abstract
] - BaseClass 必须有一个基础实现,派生类可以调用[like
virtual
] - [签名在派生类中的
foo
应该是static
(类本身不是!)[编辑:省略]] -
参数
foo
是class Derived
/this.GetType()
(首选,不改变 BaseClass 的签名)
将其中的两个组合起来已经足够困难/不可能(?)(除了 4。),但也许有一些聪明的解决方法,我会尽我所能。最后附上一些伪代码,以更好地体现我的意图:
public abstract class BaseClass
{
bool baseBool;
public abstract virtual static bool foo(BaseClass b1,BaseClass b2)
{
//sample code
return b1.baseBool ^ b2.baseBool;
}
}
public class Derived: BaseClass
{
bool derivedBool;
public static override bool foo(Derived d1,Derived d2)
{
//sample code
return base.foo(d1,d2) && d1.derivedBool ^ d2.derivedBool;
}
}
基于lidqy接受的答案的解决方案
public abstract class BaseClass
{
bool baseBool;
public abstract bool foo(BaseClass b1,BaseClass b2);
}
public abstract class BaseClassWrappedCRTP<T>: BaseClass where T: BaseClassWrappedCRTP<T>
{
public override bool foo(BaseClass b1,BaseClass b2)
{
//sample code
return b1.baseBool ^ b2.baseBool && fooWrappedCRTP((T)b1,(T)b2);
}
protected abstract bool fooWrappedCRTP(T d1,T d2);
}
public class Derived: BaseClassWrappedCRTP<Derived>
{
bool derivedBool;
protected override bool fooWrappedCRTP(Derived d1,Derived d2)
{
//sample code
return d1.derivedBool ^ d2.derivedBool;
}
}
请注意,如果 Derived 是 abstract class Derived: BaseClassWrappedCRTP<Derived>
,我们将需要 abstract class DerivedWrappedCRTP<T>: Derived where T: DerivedWrappedCRTP<T>
以这种方式继续继承 foo
(鉴于实际需要访问非泛型 Derived
) .
解决方法
正如评论中提到的,继承和静态不适合。
根据您的说法,我认为此代码可能与您的用例相符...
//declare the mixed lists with List<IBase> to get rid of the type params
interface IBase {
bool foo(BaseClass b1,BaseClass b2);
}
public abstract class BaseClass<T> : IBase where T : BaseClass
{
bool baseBool;
//If you call Foo from a "mixed list" use non generic,base class parameters,else you get casting troubles enumerating and calling 'foo'
public bool foo(BaseClass b1,BaseClass b2)
{
//sample code
return b1.baseBool ^ b2.baseBool && fooOverride((T)b1,(T)b2);
}
protected abstract bool fooOverride(T b1,T b2);
}
public class Derived : BaseClass<Derived>
{
bool derivedBool;
protected override bool fooOverride(Derived d1,Derived d2)
{
//sample code
return d1.derivedBool ^ d2.derivedBool;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。