c# - 如果两个 T 具有相同的约束条件,如何将它们视为相等?

标签 c# reflection

假设我有两个通用方法:

static void Foo<T>(T argument) { }
static void Bar<T>(T argument) { } 

下面的代码返回false,因为两个T属于不同的类型,它们可能有不同的约束:

var flags = BindingFlags.Static | BindingFlags.NonPublic;
var foo = typeof (Program).GetMethod("Foo", flags)bar.GetParameters()[0];
var bar = typeof(Program).GetMethod("Bar", flags)foo.GetParameters()[0];
bool test = foo.ParameterType == bar.ParameterType; // false

我想写一个方法来比较两个 T 基于它们的约束,如果它们有相同的约束则返回 true。例如上面的结果应该是 true因为这两个参数都没有任何约束。

我可以使用 GetGenericParameterConstraints方法并比较类型,但我还想对 classstructnew() 约束执行检查。有没有办法使用 Reflection 来做到这一点?

最佳答案

查看GenericParameterAttributes foo.ParameterTypebar.ParameterType 实例的属性:它返回一个枚举,其中包含您的类型的所有可能属性。

你会感兴趣:

  • ReferenceTypeConstraint(如果您添加了 class 作为约束)
  • NotNullableValueTypeConstraint(如果您添加了 struct 作为约束)
  • DefaultConstructorConstraint(如果未与 NotNullableValueTypeConstraint 结合使用,您添加了 new() 作为约束)

关于c# - 如果两个 T 具有相同的约束条件,如何将它们视为相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25608427/

相关文章:

c# - 我找不到内联表达式变量的代码

c# - 如何以编程方式重建现有程序集?

c# - CodeDom : compile partial class

c# - 非泛型类型 'System.Collections.ArrayList' 不能与类型参数一起使用

c# - MyGuid.Equals(OtherGuid) 不相等?

c# - 将数据推送到列表时,对 Redis 中持有错误类型值的键进行操作

c# - 使用 Roslyn 更改文件

c# - 无法创建类型为 'DbContext' 的对象

java - 我无法创建嵌套类的实例,也无法初始化字段。我想通过单元测试

c# - 无法加载一种或多种请求的类型。检索加载程序异常