声明实现通用接口的 C# 类
假设我有一个空接口类 IBaseInterface,它仅用于将实现类“标记”为接口本身。
有什么办法可以做这样的事情吗?
例如:
public class MyClass : T where T : IBaseInterface
{
}
Suppose I have an empty interface class IBaseInterface which is used only to "label" implementing classes as being interfaces themselves.
Is there any way to do something like this?
For example:
public class MyClass : T where T : IBaseInterface
{
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,你不能这样做,因为编译器必须在声明类时知道该类实现哪个接口。您可以在接口中使用通用参数 ,但必须指定实际接口。
No, you can't do that, since the compiler has to know which interface the class implements when you declare the class. You can have generic parameters to the interface, but the actual interface has to be specified.
不是这样的,没有。我强烈建议使用组合模式来尝试实现您想要的任何结果。作为替代方案,您可能会发现 DynamicProxy (或其他代理解决方案)就是您想要的我们要去的。
Not like that, there isn't. I would strongly recommend using a composition pattern to try and achieve whatever you're trying. As an alternative, you might find DynamicProxy (or some other proxy solution) is what you're going for.
您声明的类型甚至不是通用的。像这样的东西:
在某些情况下可以工作(例如,如果使用 C++ 模板而不是 .Net 泛型),但它根本不是有效的 C# 代码。
我不确定“标签”的用途是什么,但是带有属性的
接口
ClassType
是一个可以工作的enum
。The type you're declaring isn't even generic. Something like this:
could work under some circumstances (for example, if C++ templates were used instead of .Net generics), but it's simply not valid C# code.
I'm not sure what are the “labels” used for, but an interface with a property
where
ClassType
is anenum
could work.