I have the following method:
object Create(Type type)
{
var constructor = type.GetConstructor(typeof(int));
return constructor?.Invoke(new object[] {42});
}
This method works for the most of the types, either finding a constructor and invoking it, ot returning null. But, when passed the following type, it throws System.Reflection.AmbiguousMatchException
:
class C<T>
{
public C(int v) { Console.WriteLine("int"); }
public C(T v) { Console.WriteLine("T"); }
}
Create(typeof(C<int>));
This is expected, as there are two constructors with the same signature, but the question is: how to invoke a specific constructor (in this case, the one which will print "int"
)? If I use GetConstructors()
and enumerate them, I get two exactly same constructors. It seems that ConstructorInfo
and ParameterInfo
APIs do not provide any info to distinguish them: both are non-generic methods and parameter types of both are Int32
.
The same question also applies to methods other than constructors which follow the same pattern.
Aucun commentaire:
Enregistrer un commentaire