【问题标题】:C# Generics How Can I get the type passed as an argument for a generic method with no object type as a parameter?C# Generics 如何获取作为参数传递给没有对象类型作为参数的泛型方法的类型?
【发布时间】:2018-11-19 03:56:27
【问题描述】:

我需要一个方法来找到一个为这样的泛型方法调用的参数的原始类型:

public GetGenericArgumentName<T>() where T : IFoo
{
        StackFrame fr = new StackFrame(0, true);
        StackTrace st = new StackTrace(fr);
        var ga = fr.GetMethod().GetGenericArguments();

        foreach (var item in ga)
        {
            Console.WriteLine(item.Name);
        }
}

但我无法在调用者处获得原始类型。

假设我必须从 IFoo 派生类

public class Foo : IFoo {}
public class Foo2 : IFoo {}

如果我使用以下方法调用它们,我希望得到这些结果:

/* 1 */ GetGenericArgumentName<Foo>()
/* 2 */ GetGenericArgumentName<Foo2>()

对于第一个,我期望 Foo 作为结果,而对于第二个 Foo2。 我错过了什么?

【问题讨论】:

  • 您的代码为我生成了您预期的输出。你看到了什么输出?
  • 看起来像 XY 问题。你想做什么?
  • 它将 T 显示为输出。

标签: c# generics inheritance reflection


【解决方案1】:

您根本不需要使用堆栈跟踪 - 只需使用 typeof(T):

Console.WriteLine(typeof(T).Name);

第一次调用会打印Foo,第二次调用会打印Foo2

这比上栈更简单、更可靠、更高效。

【讨论】:

  • 简单而完美。有时答案很简单,你看不到。谢谢黛西。
猜你喜欢
  • 1970-01-01
  • 2013-05-05
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 2019-02-27
  • 2022-11-28
  • 2019-03-05
  • 1970-01-01
相关资源
最近更新 更多