简体   繁体   中英

How to put an interface constraint on a generic method in C# 3.5?

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?

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

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?

您不能要求T是一个接口,因此您必须在运行时使用反射来断言。

If possible, I went with a solution like this. It only works if you want several specific interfaces (eg 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 } 

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