पूरी तरह से प्रकार प्रणाली से निपटने के लिए, मैं आप प्रत्यावर्तन को संभालने के लिए, उदाहरण के लिए की जरूरत है IList<T>
: ICollection<T>
: IEnumerable<T>
, जिसके बिना आप नहीं जानते कि IList<int>
अंत में IEnumerable<>
लागू करता है।
/// <summary>Determines whether a type, like IList<int>, implements an open generic interface, like
/// IEnumerable<>. Note that this only checks against *interfaces*.</summary>
/// <param name="candidateType">The type to check.</param>
/// <param name="openGenericInterfaceType">The open generic type which it may impelement</param>
/// <returns>Whether the candidate type implements the open interface.</returns>
public static bool ImplementsOpenGenericInterface(this Type candidateType, Type openGenericInterfaceType)
{
Contract.Requires(candidateType != null);
Contract.Requires(openGenericInterfaceType != null);
return
candidateType.Equals(openGenericInterfaceType) ||
(candidateType.IsGenericType && candidateType.GetGenericTypeDefinition().Equals(openGenericInterfaceType)) ||
candidateType.GetInterfaces().Any(i => i.IsGenericType && i.ImplementsOpenGenericInterface(openGenericInterfaceType));
}
स्रोत
2012-02-08 15:41:31
यह एक बहुत ही सुरुचिपूर्ण समाधान है! एसओ पर मैंने जो कुछ देखा है, वह फोरैच लूप या लंबे LINQ प्रश्नों का उपयोग करता है। ध्यान रखें कि इसका उपयोग करने के लिए, आपको .NET Framework 3.5 होना चाहिए। –
मुझे सलाह है कि आप इसे एक विस्तार विधि ला लाएं http://bit.ly/ccza8B - इसे काफी अच्छी तरह साफ कर देगा! –
आपकी ज़रूरतों के आधार पर, आपको लगता है कि आपको वापस आने वाले इंटरफेस पर दोबारा उपयोग करने की आवश्यकता है। –