gpt4 book ai didi

c# - 如何通过反射获得诸如 `new()` 的约束。 ()

转载 作者:行者123 更新时间:2023-11-30 13:06:47 27 4
gpt4 key购买 nike

例如:

泛型参数T可以包含很多约束:

public Class<T> where T : class, IDisponse, new()
{
}

如何通过反射获取T的所有约束?

我已经知道了:

var t = typeof(Class<>).GetGenericArguments()[0]
t.IsValueType // should be struct?
t.GetGenericParameterConstraints() // should be IDisponse or other type?

但是如何获取其他约束:

  • 新()

最佳答案

您可以使用 Type.GenericParameterAttributes属性:

Gets a combination of GenericParameterAttributes flags that describe the covariance and special constraints of the current generic type parameter.

即它返回通用参数约束的按位掩码。例如。如果你想检查是否有 new() 约束:

var attributes = t.GenericParameterAttributes;
if ((attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0)
//....

对于 class 约束验证,您应该检查 ReferenceTypeConstraint 标志。

关于c# - 如何通过反射获得诸如 `new()` 的约束。 (),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43697793/

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