gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:40:02 25 4
gpt4 key购买 nike

请看下面的代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com