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

雨燕双飞 提交于 2020-02-21 12:37:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!