user1557020
user1557020

Reputation: 301

How do i find interfaces that are anyhow related to the class?

I have an issue, i need to list all the interfaces that are anyhow related to the class? – For ex:

class Test : interface1
{
    public int var1;

    classA obj1;
    classB obj2;
    classC obj3;
}

class classA: interface2
{
    testclass obj;
}

class classB: interface3
{
}

class classC: interface4
{
}

class testclass: testinterface
{ 
   myinterface objInterface;
}
interface myinterface{}

My question is how do I list all the interfaces of class Test (it should return all the interfaces anyhow related to the class ex:. interface1, interface2 etc.,).

Anyone help me please?

Thanks in advance

Upvotes: 0

Views: 219

Answers (1)

Raphaël Althaus
Raphaël Althaus

Reputation: 60493

With your current code (almost nothing public, fields instead of properties, etc...), you could do something like that :

var type = typeof(Test);
var interfaces = type.GetInterfaces().ToList();
interfaces.AddRange(type.GetFields(BindingFlags.NonPublic|BindingFlags.Instance)
     .SelectMany(x => x.FieldType.GetInterfaces()));

this won't retrieve interfaces of public int var1, as it's... public.

This probably won't fit your exact needs, but without real code and real expected result, it's quite hard to give a better answer.

EDIT

With recursion and your sample, in a console app :

private static void Main()
 {
     var type = typeof(Test);
     var interfaces = type.GetInterfaces().ToList();
     GetRecursiveInterfaces(type, ref interfaces);

 }

 private static IList<Type> GetFieldsType(Type type)
 {
     return type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Select(m => m.FieldType).ToList();
 }

 private static void GetRecursiveInterfaces(Type type, ref List<Type> interfaces)
 {
     foreach (var innerType in GetFieldsType(type))
     {
         interfaces.AddRange(innerType.IsInterface 
                             ? new[] { innerType } 
                             : innerType.GetInterfaces());
         GetRecursiveInterfaces(innerType, ref interfaces);
     }
 }

Upvotes: 1

Related Questions