Reputation: 6136
The problem is that Type.GetInterfaces() returns all interfaces that a class implements, this includes any interfaces that are defined/implemented by inherited base classes. I'm running into problems when I'm trying to find out just the interfaces that a class locally references / implements (so excluding any interfaces referenced/defined within a base class).
I want to do something similar to type.GetProperties() which can take BindingFlags, so the following code will get all public/private properties that are declared inside the type being referenced (and all properties declared in base classes are excluded).
type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
I've tried the following, but it fails as ".DeclaringType" is always null.
foreach (var implementedInterface in type.GetInterfaces())
{
if (implementedInterface.DeclaringType == type)
{
locallyDefinedInterfaces.Add(implementedInterface);
}
}
Upvotes: 1
Views: 816
Reputation: 1563
The reason that declared type is null, is probably because it is null... (since the interface is not declared within any type). Just an insight
Upvotes: 0
Reputation: 465
How about to use the is
operator to check if the class is of that type.
e.g
class Program
{
static void Main(string[] args)
{
MyClass c = new MyClass();
MyClass1 c2 = new MyClass1();
var b = c is IInterface;
Console.WriteLine(b); //False
Console.WriteLine(c2 is IInterface); //True
Console.ReadKey();
}
}
class MyClass
{
}
class MyClass1 : IInterface
{
}
interface IInterface
{
}
Upvotes: -1
Reputation: 38820
Can you not populate a collection with all interfaces it defines. Then, for each class starting from the one your target class derives from, get all interfaces that that class implements, removing from your list as you go. Repeat-and-rinse until you have no more base-classes. Whatever remains in your list are interfaces solely implemented by your original class.
Note: There may well be better ways of doing this, this is just a suggestion.
Upvotes: 3