简体   繁体   中英

C# Generics How Can I get the type passed as an argument for a generic method with no object type as a parameter?

I need a method to find the original type of an argument called for a generic method like this:

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);
        }
}

But I couldn't get the original type at the caller.

Let's say, I have to derived classes from IFoo

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

If I call them with the following methods I expect these results:

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

For the first one, I expected Foo as result, and for the second Foo2. What am I missing?

You don't need to use stack traces at all there - just use typeof(T) :

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

That will print Foo for the first call and Foo2 for the second call.

This is simpler, more reliably and more efficient than going up the stack.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM