lundi 3 juin 2019

Reflection: Check if Type will fulfill new() constraint [duplicate]

This question already has an answer here:

I have a generic function with a new() constraint:

public void DoMagicStuff<T>() where t:new() {
  // do something
}

I call this function from within a loop over every type of an assembly:

foreach (var type in baseType.Assembly.GetTypes())
{
   MethodInfo method = GetMethod<LiteDbQueue>(q => q.DoMagicStuff<object>());
   CallGenericMethod(this, method, baseType, type, null);
}

This loop works fine if the Type inside the loop fits the new() constraint. But if that type does not have a new()-constructor (e.g. a static class) I receive an error

(Typename)', on 'Void DoMagicStuffT' violates the constraint of type 'T'.

I want to validate within the Loop if the Type fulfills the new() - constraint. So something like:

if (type.IsNewable()) { ... }

How can this be done?


Just for completion: The following methods are used to "cast" my types for the generic method. These work fine and are not really part of my problem:

public MethodInfo GetMethod<T>(Expression<Action<T>> expr) {
   return ((MethodCallExpression)expr.Body).Method.GetGenericMethodDefinition();
}

public object CallGenericMethod(object baseObject, MethodInfo method, Type baseType, Type entityType, object[] parameters)
{
   MethodInfo genericMethod = method.MakeGenericMethod(entityType);
   var paams = genericMethod.GetParameters();
   var retVal = genericMethod.Invoke(baseObject, parameters);
   return retVal;
}





Aucun commentaire:

Enregistrer un commentaire