我正在尝试创建一个通用接口(interface),其中一个方法将返回一个 T,它也可以是一个接口(interface),这在 C# 中可能吗?
public interface IGetCard<T>
{
T WithBoard<T>(string boardName);
}
然后,为了实现这一点:
public class GetCard : IGetCard
{
public IGetCard WithBoard<IGetCard>(string boardName)
{
// ...do stuff...
return this;
}
}
我的目的是从实现该接口(interface)的各种类中实现该接口(interface)方法,例如:
public class DisplayCard : IDisplayCard, IGetCard
{
public IDisplayCard WithBoard<IDisplayCard>(string boardName)
{
// ...do stuff...
return this;
}
}
实现这一目标的最佳替代方案是什么?
最佳答案
只需在类定义中指定通用参数即可:
public interface IGetCard<T>
{
// be aware that I omitted the <T> from the signature, as T is
// already defined on the class-level
T WithBoard(string boardName);
}
public class GetCard : IGetCard<MyCard>
{
public GetCard WithBoard(string boardName)
{
// ...do stuff...
return this;
}
}
当然,如IGetCard<MyCard>
和IGetCard<YourCard>
是完全不同的接口(interface),没有任何共同点,您也可以从您的类中实现这两个接口(interface):
public class DisplayCard : ICard<MyCard>, IGetCard<YourCard>
{
public MyCard WithBoard(string boardName)
{
// ...do stuff...
return ...;
}
public YourCard WithBoard(string boardName)
{
// ...do stuff...
return ...;
}
}
关于c# - 我可以在 C# 中声明一个接口(interface)方法来返回泛型接口(interface)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52055244/