java C#中的匿名内部类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4770180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 07:56:45  来源:igfitidea点击:

Anonymous inner classes in C#

c#javaclosureswicketanonymous-inner-class

提问by cdmckay

I'm in the process of writing a C# Wicket implementation in order to deepen my understanding of C# and Wicket. One of the issues we're running into is that Wicket makes heavy use of anonymous inner classes, and C# has no anonymous inner classes.

我正在编写 C# Wicket 实现,以加深我对 C# 和 Wicket 的理解。我们遇到的问题之一是 Wicket 大量使用匿名内部类,而 C# 没有匿名内部类。

So, for example, in Wicket, you define a Link like this:

因此,例如,在 Wicket 中,您可以像这样定义一个链接:

Link link = new Link("id") {
    @Override
    void onClick() {
        setResponsePage(...);
    }
};

Since Link is an abstract class, it forces the implementor to implement an onClick method.

由于 Link 是一个抽象类,它强制实现者实现一个 onClick 方法。

However, in C#, since there are no anonymous inner classes, there is no way to do this. As an alternative, you could use events like this:

但是,在C#中,由于没有匿名内部类,所以没有办法做到这一点。作为替代方案,您可以使用这样的事件:

var link = new Link("id");
link.Click += (sender, eventArgs) => setResponsePage(...);

Of course, there are a couple of drawbacks with this. First of all, there can be multiple Click handlers, which might not be cool. It also does not force the implementor to add a Click handler.

当然,这有几个缺点。首先,可以有多个 Click 处理程序,这可能不太酷。它也不强制实现者添加 Click 处理程序。

Another option might be to just have a closure property like this:

另一种选择可能是只有这样的闭包属性:

var link = new Link("id");
link.Click = () => setResponsePage(...);

This solves the problem of having many handlers, but still doesn't force the implementor to add the handler.

这解决了有许多处理程序的问题,但仍然不强制实现者添加处理程序。

So, my question is, how do you emulate something like this in idiomatic C#?

所以,我的问题是,你如何在惯用的 C# 中模拟这样的东西?

采纳答案by Matthew Manela

You can make the delegate be part of the constructor of the Link class. This way the user will have to add it.

您可以使委托成为 Link 类的构造函数的一部分。这样用户就必须添加它。

public class Link 
{
    public Link(string id, Action handleStuff) 
    { 
        ...
    }

}

Then you create an instance this way:

然后以这种方式创建一个实例:

var link = new Link("id", () => do stuff);

回答by Chris Boyd

This is what I would do:

这就是我会做的:

Retain Link as an abstract class, use a Factory to instantiate it and pass in your closure / anonymous method as a parameter for the Factory's build method. This way, you can keep your original design with Link as an abstract class, forcing implementation through the factory, and still hiding any concrete trace of Link inside the factory.

将 Link 保留为抽象类,使用工厂对其进行实例化,并将您的闭包/匿名方法作为工厂构建方法的参数传入。这样,您可以将 Link 作为抽象类保留您的原始设计,强制通过工厂实现,并且仍然在工厂中隐藏 Link 的任何具体痕迹。

Here is some example code:

下面是一些示例代码:

class Program
{
    static void Main(string[] args)
    {

        Link link = LinkFactory.GetLink("id", () =>
        // This would be your onClick method.
        {
                // SetResponsePage(...);
                Console.WriteLine("Clicked");
                Console.ReadLine();
        });
        link.FireOnClick();
    }
    public static class LinkFactory
    {
        private class DerivedLink : Link
        {
            internal DerivedLink(String id, Action action)
            {
                this.ID = id;
                this.OnClick = action;
            }
        }
        public static Link GetLink(String id, Action onClick)
        {
                return new DerivedLink(id, onClick);
        }
    }
    public abstract class Link
    {
        public void FireOnClick()
        {
            OnClick();
        }
        public String ID
        {
            get;
            set;
        }
        public Action OnClick
        {
            get;
            set;
        }
    }
}

EDIT:Actually, This may be a little closer to what you want:

编辑:实际上,这可能更接近您想要的:

Link link = new Link.Builder
{
    OnClick = () =>
    {
        // SetResponsePage(...);
    },
    OnFoo = () =>
    {
        // Foo!
    }
}.Build("id");

The beauty is it uses an init block, allowing you to declare as many optional implementations of actions within the Link class as you want.

美妙之处在于它使用了一个 init 块,允许您根据需要在 Link 类中声明尽可能多的可选操作实现。

Here's the relevant Link class (With sealed Builder inner class).

这是相关的 Link 类(使用密封的 Builder 内部类)。

public class Link
{
    public sealed class Builder
    {
        public Action OnClick;
        public Action OnFoo;
        public Link Build(String ID)
        {
            Link link = new Link(ID);
            link.OnClick = this.OnClick;
            link.OnFoo = this.OnFoo;
            return link;
        }
    }
    public Action OnClick;
    public Action OnFoo;
    public String ID
    {
        get;
        set;
    }
    private Link(String ID)
    {
        this.ID = ID;
    }
}

This is close to what you're looking for, but I think we can take it a step further with optional named arguments, a C# 4.0 feature. Let's look at the example declaration of Link with optional named arguments:

这与您正在寻找的很接近,但我认为我们可以通过可选的命名参数更进一步,这是 C# 4.0 的一项功能。让我们看一下带有可选命名参数的 Link 的示例声明:

Link link = Link.Builder.Build("id",
    OnClick: () =>
    {
        // SetResponsePage(...);
        Console.WriteLine("Click!");
    },
    OnFoo: () =>
    {
        Console.WriteLine("Foo!");
        Console.ReadLine();
    }
);

Why is this cool? Let's look at the new Link class:

为什么这很酷?让我们看看新的 Link 类:

public class Link
{
    public static class Builder
    {
        private static Action DefaultAction = () => Console.WriteLine("Action not set.");
        public static Link Build(String ID, Action OnClick = null, Action OnFoo = null, Action OnBar = null)
        {
            return new Link(ID, OnClick == null ? DefaultAction : OnClick, OnFoo == null ? DefaultAction : OnFoo, OnBar == null ? DefaultAction : OnBar);
        }
    }
    public Action OnClick;
    public Action OnFoo;
    public Action OnBar;
    public String ID
    {
        get;
        set;
    }
    private Link(String ID, Action Click, Action Foo, Action Bar)
    {
        this.ID = ID;
        this.OnClick = Click;
        this.OnFoo = Foo;
        this.OnBar = Bar;
    }
}

Inside the static class Builder, there is a factory method Build that takes in 1 required parameter (The ID) and 3 optional parameters, OnClick, OnFoo and OnBar. If they are not assigned, the factory method gives them a default implementation.

在静态类 Builder 中,有一个工厂方法 Build,它接受 1 个必需参数(ID)和 3 个可选参数 OnClick、OnFoo 和 OnBar。如果它们没有被分配,工厂方法会给它们一个默认的实现。

So in your constructor's parameter arguments for Link, you are only required to implement the methods that you need, otherwise they will use the default action, which could be nothing.

因此,在 Link 的构造函数的参数参数中,您只需要实现您需要的方法,否则它们将使用默认操作,这可能什么都没有。

The drawback, however, is in the final example, the Link class is not abstract. But it cannot be instantiated outside of the scope of the Link class, because its constructor is private (Forcing the usage of the Builder class to instantiate Link).

然而,缺点是在最后一个示例中,Link 类不是抽象的。但是它不能在Link 类的范围之外实例化,因为它的构造函数是私有的(强制使用Builder 类来实例化Link)。

You could also move the optional parameters into Link's constructor directly, avoiding the need for a factory altogether.

您还可以将可选参数直接移动到 Link 的构造函数中,从而完全不需要工厂。

回答by Neil

I started this before @meatthew's good answer - I would do almost exactly the same except - except that I would start with an abstract base class - so that if you did not want to go the route of an anonymous implementation you would be free to do that too.

我在@meatthew 的好答案之前就开始了这个 - 我会做几乎完全相同的事情,除了 - 除了我会从一个抽象基类开始 - 这样如果你不想走匿名实现的路线,你就可以自由地做那个也是。

public abstract class LinkBase
{
    public abstract string Name { get; }
    protected abstract void OnClick(object sender, EventArgs eventArgs);
    //...
}

public class Link : LinkBase
{
    public Link(string name, Action<object, EventArgs> onClick)
    {
        _name = Name;
        _onClick = onClick;
    }

    public override string Name
    {
        get { return _name; }
    }

    protected override void OnClick(object sender, EventArgs eventArgs)
    {
        if (_onClick != null)
        {
            _onClick(sender, eventArgs);
        }
    }

    private readonly string _name;
    private readonly Action<object, EventArgs> _onClick;

}