Reputation: 14787
I have seen answers on SO with similar questions but did not find one addressing all criteria below.
How can I determine whether class B meets the following criteria when B inherits from A:
[B]
does not implement any [additional]
interfaces (generic or not).[A]
implements a generic interface with its own type as the generic parameter?The following
object o = new SomeObject();
bool result = (o.GetType().GetInterfaces()[0] == typeof(IKnownInterface<???>));
// ??? should be typeof(o). How to achieve this?
I know I can get the interface name string from the type which is something like "NameSpace.ClassName+IKnownInterface'1[[SomeType, ModuleName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"
but this does not seem intuitive or safe. Plus the '1
notation is incremental based on the number of generic types used for that interface.
I am either going about this the wrong way or missing something silly here. Please advise.
Upvotes: 2
Views: 620
Reputation: 21752
This should do the trick
//get the two types in question
var typeB = b.getType()
var typeA = typeB.BaseType;
var interfaces = typeA.GetInterfaces();
//if the length are different B implements one or more interfaces that A does not
if(typeB.GetInterfaces().length != interfaces.length){
return false;
}
//If the list is non-empty at least one implemented interface satisfy the conditions
return (from inter in interfaces
//should be generic
where inter.IsGeneric
let typedef = inter.GetGenericTypeDefinition()
//The generic type of the interface should be a specific generic type
where typedef == typeof(IKnownInterface<>) &&
//Check whether or not the type A is one of the type arguments
inter.GetGenericTypeArguments.Contains(typeA)).Any()
Upvotes: 2
Reputation: 2205
try:
o.GetType().GetInterfaces()[0] ==
typeof(IKnownInterface<>).MakeGenericType(o.GetType())
http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx
Upvotes: 1