c# - 为什么 IsGenericParameter 对于泛型参数为假 T

标签 c# generics reflection

我有一个这样定义的方法:

public bool TryGetProperty<T>(string name, out T value)

查看此方法的 MethodInfo,我发现

methodInfo.GetParameters()[1].ParameterType.IsGenericParameter

。我希望它是 true,因为第二个参数的类型是 T。 (另一方面,methodInfo.GetParameters()[1].ParameterType.ContainsGenericParameterstrue。)

为什么在这种情况下 IsGenericParameter 为假?验证第二个参数的类型为 T 的正确方法是什么?例如,我试图通过过滤 Type.GetMethods() 的结果来找到正确的方法。

最佳答案

参数类型不是T,而是IL和Reflection调用的T& (ref T)。 IsGenericParameter 返回 false 是正确的:对于 by-ref 类型,您首先必须获取所引用的类型。

using System;
using System.Collections.Generic;

class TestClass
{
    public void TestMethod<T>(out T something)
    {
        something = default(T);
    }
}

static class Program
{
    static void Main()
    {
        var method = typeof(TestClass).GetMethod("TestMethod");
        var parameter = method.GetParameters()[0];
        Console.WriteLine("parameter.ParameterType.IsGenericParameter: " + parameter.ParameterType.IsGenericParameter);
        Console.WriteLine("parameter.ParameterType.IsByRef: " + parameter.ParameterType.IsByRef);
        Console.WriteLine("parameter.ParameterType.GetElementType().IsGenericParameter: " + parameter.ParameterType.GetElementType().IsGenericParameter);
    }
}

输出:

parameter.ParameterType.IsGenericParameter: False
parameter.ParameterType.IsByRef: True
parameter.ParameterType.GetElementType().IsGenericParameter: True

关于c# - 为什么 IsGenericParameter 对于泛型参数为假 T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18787589/

相关文章:

java - 如何让编译器禁止对上限引用进行方法调用

java - Kotlin noarg 插件 : Constructor only accessible by java reflection

c# - 如何在 C# 中将时间划分为相等的槽

c# - 使用 CaSTLe Windsor IoC 注册通用类型和服务

delphi - 测试接口(interface)是否等于类型参数

haskell - 使用反射和 DataKinds 进行类型推断

c# - 如何优化获取/设置属性修饰属性的性能?

c# - Entity Framework Core 自定义脚手架

c# - 在 Entity Framework 中使用 'Contains' 子句类似于 'IN' SQL 子句

c# - 使用 Entity Framework 将 int 时间戳转换为 DateTime