qiucw
qiucw

Reputation: 49

C# Reflection - Delegate in a generic class

// case1
public class A<T> {
    public delegate bool Compare(T a, T b);
}

// case2
public class A {
    public delegate bool Compare<T>(T a, T b);
}

Test(typeof(A<>.Compare));
Test(typeof(A.Compare<>));

void Test(Type type)
{
    // #1
}

My Question:

How to write code in position #1 to tell type is case1 or case2?

It seems there is no difference between

typeof(A<>.Compare).GetGenericArguments()[0]

and

typeof(A.Compare<>).GetGenericArguments()[0]

Thanks!

-------------edit----------------

What I want is to tell where the T of type come from. Is T defined in A or defined in Compare itself?

There may be other more complex cases, for example

public class B<T> {
    public delegate bool Compare<X>(X a, T b);
}

In this case I want to know: X is defined on Compare, and T is defined on B.

Upvotes: 1

Views: 78

Answers (1)

Rob
Rob

Reputation: 27357

Check the declaring type:

void Test(Type type)
{
    if (type.DeclaringType.IsGenericType)
        Console.WriteLine("1"); 
    else 
        Console.WriteLine("2");
}

Upvotes: 2

Related Questions