问题
I want to achieve something like this in C# 3.5:
public void Register<T>() : where T : interface {}
I can do it with class or struct, but how to do it with an interface?
回答1:
C# and the CLR don't support overall interface constraints, although you can constrain it to a particular interface (see other answers). The closest you can get is 'class' and check the type using reflection at runtime I'm afraid. Why would you want an interface constraint in the first place?
回答2:
If you are asking about adding a constraint to a specific interface, that's straightforward:
public void Register<T>( T data ) where T : ISomeInterface
If you are asking whether a keyword exists like class or struct to constrain the range of possible types for T, that is not available.
While you can write:
public void Register<T>( T data ) where T : class // (or struct)
you cannot write:
public void Register<T>( T data ) where T : interface
回答3:
You can't demand that T is an interface, so you'd have to use reflection at runtime to assert this.
回答4:
If possible, I went with a solution like this. It only works if you want several specific interfaces (e.g. those you have source access to) to be passed as a generic parameter, not any.
- I let my interfaces, which came into question, inherit an empty interface
IInterface
. - I constrained the generic T parameter to be of
IInterface
In source, it looks like this:
Any interface you want to be passed as the generic parameter:
public interface IWhatever : IInterface { // IWhatever specific declarations }
IInterface:
public interface IInterface { // Nothing in here, keep moving }
The class on which you want to put the type constraint:
public class WorldPieceGenerator<T> where T : IInterface { // Actual world piece generating code }
来源:https://stackoverflow.com/questions/1104229/how-to-put-an-interface-constraint-on-a-generic-method-in-c-sharp-3-5