繁体   English   中英

C# 调用class内部的接口方法

[英]C# call interface method within class

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

您已经明确地实现了接口,通常您不需要这样做。 相反,只需隐式实现它,并像任何其他方法一样调用它:

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

    public Rofl()
    {
        LOL();
    }
}

(注意您的实施也需要公开。)

您可能希望将演员表(this as ILol)更改为((ILol)this) 允许as cast返回null,这可能导致以后混淆错误以及编译器必须测试的错误。

不要使用as ,只是演员:

((ILol)this).LOL();
using System;

public class Entry{
      public static void Main(){
        MyClass m = new MyClass();
        m.DoWork();
    }
}

interface IDemo1{
    void DoWork();
}

interface IDemo2{
    void DoWork();
}

public class MyClass : IDemo1, IDemo2{
    
    public void DoWork(){
        Console.WriteLine("Class Do work");
        
        if(true){ // as per any condition
               ((IDemo1)this).DoWork();
        }else{
            ((IDemo2)this).DoWork();
        }
    }
  
    void IDemo1.DoWork(){
         Console.WriteLine("Demo 1 Do work");
    }
    
    void IDemo2.DoWork(){
         Console.WriteLine("Demo 2 Do work");
    }
 }  

不,如果您明确实现了该接口。 如果通过从实现的方法中删除接口名称来使其隐式,它将按您的意愿工作。

void LOL()
{
    GlobalLOLHandler.RaiseROFLCOPTER(this);
}
public Rofl()
{
    LOL();
}

你根本不需要施放。 由于ROFL实现ILOL你可以简单地调用this.LOL()甚至只是LOL();

暂无
暂无

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

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