首页 > 解决方案 > 使用 System.Reflection.MethodBase.GetCurrentMethod().DeclaringType 获取“外来”类的泛型类型

问题描述

我使用以下方法收集调用类的类型:

var type = new StackFrame(1).GetMethod().DeclaringType;

如果该类是类型,SomeType<T>我想知道 的运行时类型T,但我无法让它工作。

我有这个方法可以获取类型名称,当类型包含泛型类型时,该类型名称将被递归调用。当我使用我收集的类型运行此方法时,GetType()它可以工作并返回例如SomeType<Int32>字符串。但是当我运行使用GetCurrentMethod().DeclaringType它的方法时,它将SomeType<T>作为字符串返回。

我创建类型名称字符串的方法:

private string GetTypeString(Type type)
{
    var typeString = type.Name;

    if (type.IsGenericType)
    {
        var genericTypeNames = type.GetGenericArguments().Select(ar => GetTypeString(ar));

        // When a type is generic, it will be formatted as Type`x  (the next line of code will strip the `x)
        var strippedTypeName = typeString.Substring(0, typeString.IndexOf("`"));
        var genericTypeString = string.Join(",", genericTypeNames);
        typeString = $"{strippedTypeName}<{genericTypeString}>";
    }

    return typeString;
}

示例(显示两种方法的结果):

public class SomeType<T>
{        
}

public static class Main
{
    public void Run()
    {
        SomeType<bool> myClass = new SomeType();

        // This works, but I cannot use it in my application, because I collect the class type using StackFrame
        var type = myClass.GetType();
        var output = GetTypeString(type);  // This returns "SomeType<bool>"

        // This doesn't work:
        type = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType;
        output = GetTypeString(type);  // This returns "SomeType<T>"
}

第一个例子表明 usingGetType()给了我想要的结果。但是我不能使用它,因为我想创建类型字符串的地方我不能在类上调用 GetType()。我使用StackFrame. 第二个示例显示了当我通过 `GetMethod().DeclaringType' 获取类型时的结果。结果是不同的,而不是我正在寻找的。有没有人有任何提示或建议?

现实

public class SomeType<T>
{
    private class Log = new Log();
}

public class Log
{
    private string typeString;

    public Log()
    {
        var type = new StackFrame(1).GetMethod().DeclaringType; // This collects type of the calling class, in this case 'SomeType<T>'
        typeString = GetTypeString(type);  // This constructs the type string, but is not able to determine the type of T
    }
}

标签: c#

解决方案


推荐阅读