How can I get, for example, the expression `new ()` by reflection. ()

eg:

a general parameter T

can contain many restrictions:

public Class<T> where T : class, IDisponse, new()
{
}

      

how can i get all the constraints T

by reflection?

I already knew:

var t = typeof(Class<>).GetGenericArguments()[0]
t.IsValueType // should be struct?
t.GetGenericParameterConstraints() // should be IDisponse or other type?

      

but how to get other constraints:

  • class
  • New()
+3


source to share


2 answers


You can use the Type.GenericParameterAttributes property:

Gets a combination of GenericParameterAttributes flags that describe the covariance and special constraints of the current type parameter.

those. it returns a bitmask of general parameter constraints. For example. if you want to check if a constraint exists new()

:



var attributes = t.GenericParameterAttributes;
if ((attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0)
  //....

      

When checking constraints, class

you should check the flag ReferenceTypeConstraint

.

0


source


Are you trying to create a new instance by reflection?

Use the System.Activator class.



https://msdn.microsoft.com/en-us/library/system.activator(v=vs.110).aspx

T instance = (T)Activator.CreateInstance(typeof(T));

      

-3


source







All Articles