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
ofMyClass
in a variableclassType
, - the
Type
ofmyParam
in a variableparamType
, - the value to pass as
myParam
in a variablemyValue
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