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

标签 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

约束classnew()似乎不是由parm.GetGenericParameterConstraints()返回的。尽管 TU 有限制,但 parm.GetGenericParameterConstraints() 不返回数据。

问:如何使用反射检查此类约束?

最佳答案

您要查找的约束可以通过查看 GenericParameterAttributes 找到类型

var gpa = parm.GenericParameterAttributes;

var constraints = gpa & GenericParameterAttributes.SpecialConstraintMask;

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

关于c# - 如何使用反射分析 C# 中的特殊类型约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33762226/

相关文章:

c# - 在 xna 项目中配置模型/纹理位置的最佳方法是什么

java - 如何从参数化参数中获取参数的类型

python - Generic[T] 基类 - 如何从实例中获取 T 的类型?

c# - MSBuild 项可以使用目标设置的属性吗?

c# - 在回调时反序列化 soap 消息时出现问题

c# - UnitTest - 测试来自模拟的方法时的问题

java - 使用 Java 泛型时出现 DynamoDBMappingException

c# - 反射 PropertyInfo.GetValue

android - Android 2.2 没有完全实现反射?

c# - 如何使用反射调用带参数的非泛型静态扩展方法