获取实现接口的 class 的名称

Get name of class that implements an interface

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

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

对象将始终实现此接口,但它可能已在对象继承的 class 上实现。我怎样才能得到实现了这个接口的 class 的名称?

例子应该给出这些结果

public class MyClass : IMyInterface {

}

public class MyHighClass : MyClass {

}

public class MyPlainClass {

}

public class PlainInheritedClass : MyPlainClass, IMyInterface {

}

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

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

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

编辑/解释

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

我的大部分实体都没有继承任何东西,只是实现了接口。但是我有几个实体确实继承自另一个对象。有时他们继承的对象实现接口,有时对象本身将实现接口。

当我设置值时,我使用实体,entity framework 计算出要更新哪个 table。但是当我 "unset" 属性 时,我正在使用我自己的 SQL 语句。为了创建我自己的 SQL 语句,我需要找出哪个 table 具有我需要更新的列。

我不能使用 entity framework 仅基于类型加载实体,因为 .Where 在通用 DbSet class.

上不存在

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

UPDATE tableX SET interfaceProperty = NULL WHERE interfaceProperty = X

刚才想多了,功能很简单。只是装箱有人需要一些类似的东西,在这里,我已经把它变成了通用的。您始终可以将其改为扩展。

代码一直向下交互,到达基础 class,然后在返回树的过程中检查每个 class。

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));