我想要一个泛型类,它可以根据派生类定义的泛型类型调用方法。为此,我实现了一个基本接口和一个通用接口,其中基本接口是通用的,并且也派生自基本接口。
在通用接口中,我想要一个基于基本接口的类型 T 的方法。
之后我想实现一个基于通用接口的类,它应该能够调用通用方法。这是示例代码:
public interface BaseInterface
{ }
public interface GenericInterface<T> : BaseInterface where T : BaseInterface
{
void Foo(T t);
}
public class C<T> : GenericInterface<T> where T : BaseInterface
{
public C()
{
// None of these works
Foo(this);
Foo((T)this);
Foo((BaseInterface)this);
}
public void Foo(T t) { }
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在这里实现我想要的行为?
这里的错误信息是:
cannot convert from 'C<T>' to 'T'
Run Code Online (Sandbox Code Playgroud)
在我看来这应该是可能的,因为 C 派生自 BaseInterface,而 BaseInterface 是 T
以下是 C# 中的 Curiously Recurring 模板所需的内容。
public interface BaseInterface { }
public interface GenericInterface<T> : BaseInterface where T : GenericInterface<T>
{
void Foo(T t);
}
public abstract class C<T> : GenericInterface<T> where T : C<T>
{
public abstract void Foo(T t);
}
Run Code Online (Sandbox Code Playgroud)
现在您可以继续实现一个真正的类:
public class D : C<D>
{
public D()
{
Foo(this);
Foo((D)this);
}
public override void Foo(D t) { }
}
Run Code Online (Sandbox Code Playgroud)
效果很好。
但是,Foo((BaseInterface)this);
在此代码中调用永远不会起作用。这根本没有意义。
归档时间: |
|
查看次数: |
814 次 |
最近记录: |