如何使用反射分析C#中的特殊约束?
请参阅以下代码:如何使用反射分析C#中的特殊约束?,c#,generics,reflection,C#,Generics,Reflection,请参阅以下代码: 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() {
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);
}
}
}
}
}
}
约束class
和new()
似乎不是由parm.GetGenericParameterConstraints()
返回的。虽然对T
和U
parm有约束,但GetGenericParameterConstraints()
不返回数据
问:如何使用反射检查此类约束?您要查找的约束可以通过查看
类型的
var gpa = parm.GenericParameterAttributes;
var constraints = gpa & GenericParameterAttributes.SpecialConstraintMask;
if ((constraints & GenericParameterAttributes.DefaultConstructorConstraint) != 0)
{
// yippie!
}
var gpa = parm.GenericParameterAttributes;
var constraints = gpa & GenericParameterAttributes.SpecialConstraintMask;
if ((constraints & GenericParameterAttributes.DefaultConstructorConstraint) != 0)
{
// yippie!
}