Checking a general type constraint

Is it possible to write something that fails either at compilation or at runtime (i.e. in any way) when only one of these methods is called?

public static void Register<TInterface, TImplementation>()
    where TImplementation : class, TInterface
{
}
public static void RegisterRestrictive<TInterface, TImplementation>()
    where TInterface : class
    where TImplementation : class, TInterface
{
}

The following will pass as, for example:

public interface IInterface
{
}

public class Implementation : IInterface
{
}


public void Test()
{
    Register<IInterface, Implementation>();
    RegisterRestrictive<IInterface, Implementation>();
}

I do not think so, because you can not expand the structure?

Asking because of this https://github.com/aspnet/DependencyInjection/pull/624

+4
source share
2 answers

The question is, as far as I understand:

class C<T, U> where T : class, U where U : class { }
class D<T, U> where T : class, U { }

Is there a law legal for Dthat is not legal for C?

Not if Uand Tare private types. That is, types in which there are no type parameters. As John Hannah says, an open type can cause a problem:

class N<T, U> where T : class, U { C<T, U> c; D<T, U> d; }

D , .

, , :

C U.

D, T , , . U T T, - T ( ) . , U .

, #, CLR, JIT , U ! # , , U, , U .

, a U , , , - , , . , , , , , , .

, .


:

, ,

class B<T> { public virtual void M<U>(U u) where U : T {} }
class D : B<int> { public override void M<U>(U u) { } }

, # , where U : int. M - , int.

IL, CLR , " -- " . codegen , -, , jit , , # 2.

+7

-, , (.. - ) ?

, :

public static void CallThem<TA, TB>()
    where TB : class, TA
{
    Register<TA, TB>();         // Fine
    RegisterRestrictive<TA, TB>(); // CS0452
}

, TInterface TImplementation , , , , - , API, .

.

+4

Source: https://habr.com/ru/post/1692795/


All Articles