Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用反射分析C#中的特殊约束?_C#_Generics_Reflection - Fatal编程技术网

如何使用反射分析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!
}