我们如何使用内部匿名的c#接口?

时间:2014-02-20 07:07:23

标签: c# java

我正在使用将一个Java程序转换为C#,其中我遇到了使用匿名接口的问题。请告诉我如何在C#中实现这一目标 这是java中的示例,我们如何为C#编写内部匿名?

interface Test
{
    public void wish();
}

class Main
{
    public static void main(String[] args)
    {
        Test t=new Test()
        {
            public void wish()
            {
                System.out.println("output: hello how r u");
            }
        };
        t.wish();
    }
}

5 个答案:

答案 0 :(得分:2)

试试这个

public interface Test  
{  
    public void wish();  
}  
class Main  : Test
{  
    public void wish(){
    //Your code
    }
}  

答案 1 :(得分:1)

您无法在C#中实例化接口。 C#中的匿名类型基本上只是属性集,因此它们不能在其中定义方法,也不能实现接口。

您可以创建一个实现接口的类,在其中包含Action字段,并将要调用的方法分配给该字段,如下所示:

using System;

public interface ITest
{
    void Wish();
}

public class Test : ITest
{
    private readonly Action _wishAction;

    public Test(Action wish)
    {
        _wishAction = wish;
    }

    public void Wish()
    {
        _wishAction();
    }
}

class Program
{ 
    public static void Main(String[] args)
    {
        Test t = new Test(() => Console.WriteLine("output: hello how r u"));
        t.Wish();
    }  
}

或者,您可以使用lambda:

class Program
{ 
    public static void Main(String[] args)
    {
        Action wish = () => Console.WriteLine("output: hello how r u");
        wish();
    }  
}

答案 2 :(得分:1)

您必须implement其他课程中的Test界面MyTest。然后只需要实例化MyTest类并将其分配给Test实例的实例。请参阅以下代码:

interface Test  
{  
    void wish();  
}

class MyTest : Test
{  
    public void wish()
    {  
        System.out.println("output: hello how r u");  
    }  
}

static class Program
{  
    [STAThread]
    static void main()  
    {  
        Test t=new MyTest();  
        t.wish();  
    }  
}  

答案 3 :(得分:0)

您在C#中没有与Java中相同的匿名类。

执行上述操作的C#方法是使用委托而不是接口:

public delegate void Wisher();

class Main  
{  
    public static void main(String[] args)  
    {  
        Wisher t = () => Console.WriteLine("output: hello how r u");  
        t();
    }  
}  

根据您的使用情况,您可以使用System.Action委托类型而不是自定义委托类型。

答案 4 :(得分:0)

可悲的是,C#doesn't allow匿名类以相同的方式实现接口Java does

即。 java代码:

Test t = new Test(){
    public void wish(){ ...
}

将'伪C#'等同于

ITest t = new /* AnonClass : */ ITest 
{
     public void wish()
     { ...
     }
}

当然不会编译。

正如其他人所提到的,你需要在命名类上实现接口并实例化它(尽管直接在Main上实现接口也不是我的第一选择。在嵌套上或许?)。