Please see the following code:
public class GenericTest2
{
public class MyGenericClass<T, U, V, W>
where T : class
where U : new()
where V : struct
where W : System.IO.StringWriter
{
}
public static void Test()
{
Assembly a = Assembly.GetAssembly(typeof(GenericTest));
foreach (Type t in a.GetTypes()) {
Console.Out.WriteLine(t.FullName);
if (t.IsGenericType) {
Console.Out.WriteLine("\tIsGeneric!");
foreach (Type parm in t.GetGenericArguments()) {
Console.Out.WriteLine("\tGeneric parameter: " + parm.Name);
Type[] constraints = parm.GetGenericParameterConstraints();
for (int i = 0; i < constraints.Length; i++) {
Console.Out.WriteLine("\t\t constraint " + i + ": name = " + constraints[i].Name);
Console.Out.WriteLine("\t\t constraint " + i + ": fullname = " + constraints[i].FullName);
}
}
}
}
}
}
This code will output something like this:
ProcessCSharpAssemblies.Program
ProcessCSharpAssemblies.GenericTest2
ProcessCSharpAssemblies.GenericTest2+MyGenericClass`4
IsGeneric!
Generic parameter: T
Generic parameter: U
Generic parameter: V
constraint 0: name = ValueType
constraint 0: fullname = System.ValueType
Generic parameter: W
constraint 0: name = StringWriter
constraint 0: fullname = System.IO.StringWriter
The constraints class
and new()
do not seem to be returned by parm.GetGenericParameterConstraints()
. Though there are constraints for T
and U
parm.GetGenericParameterConstraints()
does not return data.
Q: How can I check for these kind of constraints using reflection?
Aucun commentaire:
Enregistrer un commentaire