How to set an interface restriction on a common method in C # 3.5?

I want to achieve something similar in C # 3.5:

public void Register<T>() : where T : interface {}

I can do it using a class or structure, but how to do it using an interface?

+5
source share
4 answers

C # and the CLR do not support common interface restrictions, although you can limit it to a specific interface (see other answers). Closest you can get a "class" and check the type using reflection at runtime, I'm afraid. Why do you first need an interface limitation?

+4
source

If you ask about adding a constraint to a specific interface, this is simple:

public void Register<T>( T data ) where T : ISomeInterface

, class struct T, .

:

public void Register<T>( T data ) where T : class // (or struct)

:

public void Register<T>( T data ) where T : interface
+6

, T , , .

0

, . , , (, , ), , -.

  • , , IInterface.
  • T IInterface

:

  • , :

    public interface IWhatever : IInterface
    {
        // IWhatever specific declarations
    }
    
  • IInterface:

    public interface IInterface
    {
        // Nothing in here, keep moving
    }
    
  • , :

    public class WorldPieceGenerator<T> where T : IInterface
    {
        // Actual world piece generating code
    }
    
0
source

All Articles