c# - 使用 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
}
}
解决方案
推荐阅读
- r - 每两列将函数应用于数据框的列,将该函数的结果存储在列表中,然后将该列表作为列插入
- spring - Spring 验证器未检测到错误
- html - 选择列表中类的最后一个元素
- reactjs - 为什么 Context API 在高频更新方面比 Redux 差?
- excel - 如果单元格包含今天的日期,则删除整行
- mysql - 用where条件一个查询更新mysql表的每一行
- r - 根据R中的ID和年份计算第一个差异
- elasticsearch - 失败 | java.lang.NoClassDefFoundError: org/elasticsearch/action/DocWriteRequest
- django - 如何从订单表中获取所有数据,但从 django 中的订单项目表中获取一些数据
- perforce - Perforce 错误 - 警告:无法从非流客户端标题提交