如何使用反射分析C#中的特殊约束?

时间:2015-11-17 16:32:41

标签: 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()
    {
        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);
                    }
                }
            }
        }

    }

}

此代码将输出如下内容:

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

class似乎没有返回约束new()parm.GetGenericParameterConstraints()。虽然TU parm.GetGenericParameterConstraints()存在约束,但不会返回数据。

问:如何使用反射检查这些约束?

1 个答案:

答案 0 :(得分:4)

通过查看Type的{​​{3}},可以找到您要查找的约束。

var gpa = parm.GenericParameterAttributes;

var constraints = gpa & GenericParameterAttributes.SpecialConstraintMask;

if ((constraints & GenericParameterAttributes.DefaultConstructorConstraint) != 0)
{
    // yippie!
}