C # common methods, is it possible to deduce a parameter type from a type definition of a type type?

Is there a way to get the following (non-compiled) code? I did not find a solution for this.

public class Factory{ public static T Get<T>(V v) where T : BaseClass<V> { T someObject = DIContainer.Resolve<T>(); someObject.Set(v); } } 

T is a parameter of the usual generic type, used to define the generic "Get" method, but has a type constraint that contains the generic type itself. Now the method must determine a parameter whose type is determined by a parameter of a general type, determined by a parameter of the general type of method.
BaseClass will define a Set method that receives a type argument of its type type parameter.
So, you can call Factory.Get<A<B>>(someObjectCastableToB); .

This will work by defining the Get as Get method with a different constraint on V. But then the call will be Factory.Get<A<B>,B>(....) , which is not so nice since the declaration B exists twice.

Thanks!

+4
source share
1 answer

Unlike C ++ templates, where you can "template templates" or "partial specialization" , C # general arguments can only go to the depth of the announcement site, and general restrictions can only tell you about the origin and nothing more. If you want to be able to refer to the common argument of one of your common arguments, the only way to do this, as in your example, is by using the general restriction on the hereditary line ( T : BaseClass<V> ), and then V must also be identified in general signature. You need something like below.

 public class Factory{ public static T Get<T, V>(V v) where T : BaseClass<V> { T someObject = DIContainer.Resolve<T>(); someObject.Set(v); } } 

All I added here is a generic V argument for your method signature. Again, if you did not have a base class for binding V to, you would not be able to do much in your situation. For example, if the runtime type of T itself was general and not its base class, you would be stuck, as in the example below, which does not compile.

 public class Factory{ public static T Get<T, V>(V v) where T : T<V> { T someObject = DIContainer.Resolve<T>(); someObject.Set(v); } } 
+2
source

All Articles