作者:拍友2602939213 | 来源:互联网 | 2023-05-24 13:19
在C#中是否有任何方法可以使用通用类型,它始终是接口中的实现类型?像这样的东西:
interface Foo
{
this GetOtherThis();
}
class Bar : Foo
{
Bar GetOtherThis();
}
Jon Skeet..
5
在C#中是否有任何方法可以使用通用类型,它始终是接口中的实现类型?
不会.到目前为止给出的答案不满足这个要求,原因有两个:
您始终可以使用不同的接口实现接口 T
interface IFoo
{
T GetOtherThis();
}
public class NotAString : Foo
{
string GetOtherThis() { ... }
}
这可以通过约束在某处修复:interface IFoo where T : IFoo
但这仍然不能阻止这种情况;
public class Good : IFoo { ... }
public class Evil : IFoo { /* Mwahahahaha */ }
无论如何继承都会破坏它:
interface IFoo
{
T GetOtherThis();
}
public class WellBehaved : IFoo
{
WellBehaved GetOtherThis() { ... }
}
public class BadlyBehaved : WellBehaved
{
// Ha! Now x.GetOtherThis().GetType() != x.GetType()
}
基本上C#中没有任何内容可以为你强制执行.如果您认为接口实现是合理的,那么通用接口方案仍然有用,但您需要了解其局限性.
1> Jon Skeet..:
在C#中是否有任何方法可以使用通用类型,它始终是接口中的实现类型?
不会.到目前为止给出的答案不满足这个要求,原因有两个:
您始终可以使用不同的接口实现接口 T
interface IFoo
{
T GetOtherThis();
}
public class NotAString : Foo
{
string GetOtherThis() { ... }
}
这可以通过约束在某处修复:interface IFoo where T : IFoo
但这仍然不能阻止这种情况;
public class Good : IFoo { ... }
public class Evil : IFoo { /* Mwahahahaha */ }
无论如何继承都会破坏它:
interface IFoo
{
T GetOtherThis();
}
public class WellBehaved : IFoo
{
WellBehaved GetOtherThis() { ... }
}
public class BadlyBehaved : WellBehaved
{
// Ha! Now x.GetOtherThis().GetType() != x.GetType()
}
基本上C#中没有任何内容可以为你强制执行.如果您认为接口实现是合理的,那么通用接口方案仍然有用,但您需要了解其局限性.