mercredi 9 novembre 2022

Using a type variable how can I specify the type of a constructor argument passed to Activator.CreateInstance?

This is NOT a question about generics.

Suppose I have a class with constructor public MyClass(int myParam){}.

And I want to construct it with Activator.CreateInstance when I have:

  • the Type of MyClass in a variable classType,
  • the Type of myParam in a variable paramType,
  • the value to pass as myParam in a variable myValue BUT it is an object.

I want to do this

public void CreateTheClass(Type classType, Type paramType, object myValue)
{  
  return Activator.CreateInstance(classType, myValue);
}

But this will throw an exception because the constructor takes an int, not an object. I don't believe it is possible to cast myValue to an int because the type (specified by paramType) is in a type variable.

Is there a way to tell Activator.CreateInstance to treat myValue as a different type? Is it possible to use a dynamic for this? Is there an alternative approach?





Aucun commentaire:

Enregistrer un commentaire