2015-10-02 31 views
-2

我有一些实体,可能会或可能不会从其他对象继承,但它们将实现一个接口,我们称它为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语句,我需要找出哪个表有我需要更新的列。

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

所以我想创建一个类似于此

UPDATE tableX SET interfaceProperty = NULL WHERE interfaceProperty = X 
+3

你做出什么样的努力? –

+0

你想要什么? –

+0

也许'typeof(MyClass).Name'? –

回答

0

我只是思前想整个事情,该功能是很容易的SQL语句。只要包住一个人需要一些东西,在这里,我已经说它是通用的。您可以始终将其作为扩展名。

代码只是interates一路下跌,基类,然后检查的方式,每个班备份通过树。

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