繁体   English   中英

获取实现接口的类的名称

[英]Get name of class that implements an interface

我有一些实体,可能会也可能不会从其他对象继承,但是它们将实现一个接口,将其称为IMyInterface。

public interface IMyInterface {
    long MyPropertyName { get; set; }
}

对象将始终实现此接口,但是它可能已在该对象继承的类上实现。 我如何获取已实现此接口的类的名称?

例子应该给出这些结果

public class MyClass : IMyInterface {

}

public class MyHighClass : MyClass {

}

public class MyPlainClass {

}

public class PlainInheritedClass : MyPlainClass, IMyInterface {

}

如果我传入MyClass,它应该返回MyClass,因为MyClass实现了接口。

如果我传入MyHighClass,它应该返回MyClass,因为MyClass是继承的,并且它实现了接口。

如果我传入PlainInheritedClass,则它应该返回PlainInheriedClass,因为它继承自MyPlainClass,但是没有实现该接口,PlainInheritedClass做到了

编辑/说明

我正在使用实体框架6。我创建了一种回收站功能,该功能允许用户删除数据库中的数据,但实际上它只是将其隐藏。 为了使用此功能,实体必须实现一个接口,该接口具有针对它的特定属性。

我的大多数实体都不继承任何东西,而只是实现接口。 但是我有几个确实从另一个对象继承的实体。 有时它们从其继承的对象实现接口,有时对象本身将实现接口。

设置值时,我使用实体,而实体框架计算出要更新的表。 但是,当我“重置”属性时,我正在使用自己的SQL语句。 为了创建自己的SQL语句,我需要找出哪个表具有需要更新的列。

我不能使用实体框架仅基于类型加载实体,因为通用DbSet类上不存在.Where

所以我想创建一个与此类似的SQL语句

UPDATE tableX SET interfaceProperty = NULL WHERE interfaceProperty = X

我只是想整个事情,功能非常简单。 只是包裹着某人需要一些比较有趣的东西,在这里,我使它变得通用了。 您总是可以将其扩展。

代码只是一直向下插入基类,然后在返回整个树的过程中检查每个类。

public Type GetImplementingClass(Type type, Type interfaceType)
{
    Type baseType = null;

    // if type has a BaseType, then check base first
    if (type.BaseType != null)
        baseType = GetImplementingClass(type.BaseType, interfaceType);

    // if type
    if (baseType == null)
    {
        if (interfaceType.IsAssignableFrom(type))
            return type;
    }

    return baseType;
}

所以我不得不以我的例子来称呼它

// result = MyClass
var result = GetClassInterface(typeof(MyClass), typeof(IMyInterface));

// result = MyClass
var result = GetClassInterface(typeof(MyHighClass), typeof(IMyInterface));

// result = PlainInheritedClass 
var result = GetClassInterface(typeof(PlainInheritedClass), typeof(IMyInterface));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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