简体   繁体   中英

Declare C# Class That Implements a Generic Interface

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
{
}

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM