代码之家  ›  专栏  ›  技术社区  ›  0xDEAD BEEF

类内的C#调用接口方法

  •  3
  • 0xDEAD BEEF  · 技术社区  · 14 年前
    interface ILol
    {
       void LOL();
    }
    
    class Rofl : ILol
    {
       void ILol.LOL()
       {
          GlobalLOLHandler.RaiseROFLCOPTER(this);
       }
       public Rofl()
       {
          //Is there shorter way of writing this or i is there "other" problem with implementation??
          (this as ILol).LOL();
       }
    }
    
    5 回复  |  直到 14 年前
        1
  •  10
  •   ladenedge    14 年前

    你已经实现了接口 explicitly

    class Rofl : ILol
    {
        public void LOL() { ... }
    
        public Rofl()
        {
            LOL();
        }
    }
    

    (请注意,您的实现还需要公开。)

        2
  •  9
  •   Stewart    14 年前

    您可能需要将演员阵容从 (this as ILol) ((ILol)this) . as-cast允许返回null,这可能会在以后导致混乱的错误,编译器必须对此进行测试。

        3
  •  5
  •   Mark Byers    14 年前

    不要使用 as

    ((ILol)this).LOL();
    
        4
  •  0
  •   Will Vousden    14 年前

    如果您显式实现接口,则不需要。如果通过从实现的方法中删除接口名使其隐式化,它将按您所希望的方式工作。

    void LOL()
    {
        GlobalLOLHandler.RaiseROFLCOPTER(this);
    }
    public Rofl()
    {
        LOL();
    }
    
        5
  •  -3
  •   cortijon    14 年前

    你根本不需要施法。自 ROFL 工具 ILOL this.LOL() 或者只是 LOL();