开发者

Declare C# Class That Implements a Generic Interface

开发者 https://www.devze.com 2023-03-18 07:30 出处:网络
Suppose I have an empty interface class IBaseInterface which is used only to开发者_JAVA百科 \"label\" implementing classes as being interfaces themselves.

Suppose I have an empty interface class IBaseInterface which is used only to开发者_JAVA百科 "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
{
}


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.


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.


The type you're declaring isn't even generic. Something like this:

class MyClass<T> : T where T : IBaseInterface

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

ClassType ClassType { get; }

where ClassType is an enum could work.

0

精彩评论

暂无评论...
验证码 换一张
取 消