简体   繁体   中英

Find out in c# if a class inherit from interface directly

i want to know if a class inherit directly from an interface or not. something like the Type.IsSubClass but for interface.

for

interface IOne{}
class Zero{}
class One:IOne{}
class Two:One{}
class Three: Zero, IOne{}

type(Three).IsSubInterface(IOne)  //should return true
type(Two).IsSubInterface(IOne)    //should return false

i tried to play with Type.GetInterfaces and Type.BaseType but couldnt' figure out the direct way to get if SubInterface is a class or not. the typeof(IOne).IsAssignableFrom isn't working for me since it's checking the whole tree of inheritance, but here I just want to check if a class directly inherit from an interface or not.

the reason behind is in efcore to audit only those entity that inherits from IAudit interface not any entity that inherits from the audited entity.

the other solution rather than IAudit i thought was to create an attribute, but my life will be much easier if i can solve this with an interface

Does this work for you?

using System;

namespace Demo
{
    interface IOne { }
    class Zero { }
    class One : IOne { }
    class Two : One { }
    class Three : Zero, IOne { }

    public static class TypeExt
    {
        public static bool IsSubInterface(this Type t1, Type t2)
        {
            if (!t2.IsAssignableFrom(t1))
                return false;

            if (t1.BaseType == null)
                return true;

            return !t2.IsAssignableFrom(t1.BaseType);
        }
    }

    class Program
    {
        static void Main()
        {
            Console.WriteLine(typeof(Three).IsSubInterface(typeof(IOne)));
            Console.WriteLine(typeof(Two).IsSubInterface(typeof(IOne)));
        }
    }
}

If the type does not implement t2 then the answer is always false .

If the type has no base class but implements t2 then it must be the implementing class, so the answer is true.

If the type implements t2 , has a base class, and that base class doesn't implement t2 then the answer is true .

Otherwise the answer is false.

This might not work for all cases; the question is: Does it work for the cases that you want it to work for?

HOWEVER: I'm not sure this is a design route that you want to go down. It seems a bit hacky. I agree with /u/Damien_The_Unbeliever's comment above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM