Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

c# - Is there a way to determine if a generic type is built from a specific generic type definition?

I've got a generic method:

Func<IEnumerable<T>, bool> CreateFunction<T>()

where T can be any number of different types. This method does a bunch of stuff using reflection and if T is an IDictionary, regardless of the the dictionary's TKey and TValue I need to execute dictionary specific code.

So the method could be called:

var f = CreateFunction<string>();
var f0 = CreateFunction<SomePocoType>();
var f1 = CreateFunction<IDictionary<string,object>>();
var f2 = CreateFunction<Dictionary<string,object>>();
var f3 = CreateFunction<SomeDerivedDictionaryType<string,object>>();

etc.

Clarification per @Andy's answer

Ultimately I want to know if T inherits from/implements IDictionary even if T itself is Dictionary or some other type that derives from that interface.

if(typeof(T) == typeof(IDictionary<,>)

doesn't work because T is the generic type not the generic type definition.

And without knowing TKey and TValue (which are not known at compile time) I can't do a comparison to any concrete type that I would know about until runtime.

The only thing that I've come up with are looking at the type's name or inspecting its method with reflection, looking for methods that would lead me to believe it is a dictionary (i.e. look for ContainsKey and get_Item).

Is there any straightforward way to make this sort of determination?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can avoid using ugly and potentially risky type name string checking using the IsGenericType and GetGenericTypeDefinition members, as follows:

var type = typeof (T);
if (typeof (IDictionary).IsAssignableFrom(type))
{
    //non-generic dictionary
}
else if (type.IsGenericType &&
         type.GetGenericTypeDefinition() == typeof (IDictionary<,>))
{
    //generic dictionary interface
}
else if (type.GetInterfaces().Any(
            i => i.IsGenericType &&
                 i.GetGenericTypeDefinition() == typeof (IDictionary<,>)))
{
    //implements generic dictionary
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...