【问题标题】:Base interface in c#c#中的基本接口
【发布时间】:2016-09-05 11:06:45
【问题描述】:

我需要某种方式来标记基接口并确定一个类是实现了基接口还是它的派生接口。 c# 不允许有“抽象接口”。有没有办法在 c# 中做到这一点?

public interface IBaseFoo
{
     void BaseMethod();
}

public interface IFoo : IBaseFoo
{
     void FooMethod();
}

public class Base
{

}

public class A : Base, IFoo
{

}

public class B : Base, IBaseFoo
{

}

现在,在下面的方法中,我需要检查 typeCls 是否实现了 IFooIBaseFoo 而没有明确指定类型。我需要一种方法来标记基本接口并在方法中识别它。 (即:如果c#允许有抽象接口,我可以检查IsAbstracttypeClas的接口属性)

public bool IsBaseFooImplemented<T>(T typeCls) where T : Base
{
     // Here I need to check if the typeCls is implemented the IFoo or IBaseFoo
}

【问题讨论】:

  • 这有点味道。你说你“需要”检查这个 - 为什么你需要检查?您认为标准 SOLID OO 无法实现的目标是什么?因为你即将打开/关闭,所以在你做之前要仔细考虑。

标签: c# reflection interface


【解决方案1】:

因为IFoo : IBaseFoo,每个实现IFoo的类也实现IBaseFoo。但不是反过来,所以你可以简单地检查typeCls is IFoo是否。

请注意,基于实现的接口改变行为通常是一种设计味道,首先绕过了接口的使用。

【讨论】:

    【解决方案2】:
    //somewhere define 
    
    static List<IBaseFoo> list = new List<IBaseFoo>();
    
    public class A : Base, IFoo
    {
        public A()
        {
            YourClass.list.add(this);
        }
    }
    
    public class B : Base, IBaseFoo
    {
        public B()
        {
            YourClass.list.add(this);
        }
    }
    

    //然后你可以检查一个类是否是IFoo。

    public bool IsBaseFooImplemented<T>(T typeCls) where T : Base
    {
         foreach(var c in list )
         {
             if(typeof(c) == typeCls) return true;
         }
         return false;
    }
    

    我还没有测试过代码,但它应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 2017-02-05
      • 1970-01-01
      • 2019-08-25
      • 1970-01-01
      • 2010-10-17
      相关资源
      最近更新 更多