匿名内部类在C# [英] Anonymous inner classes in C#
问题描述
我是为了加深我对C#和检票了解编写C#检票执行的过程。其中一个我们正在运行到的问题是,检票使得大量使用匿名内部类和C#有没有匿名内部类。
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.
因此,例如,在检票,你定义一个链接是这样的:
So, for example, in Wicket, you define a Link like this:
Link link = new Link("id") {
@Override
void onClick() {
setResponsePage(...);
}
};
由于链接是一个抽象类,它迫使实现者实现一个onClick方法。
Since Link is an abstract class, it forces the implementor to implement an onClick method.
不过,在C#中,因为没有匿名内部类,有没有办法做到这一点。作为替代方案,你可以使用像这样的活动:
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:
var link = new Link("id");
link.Click += (sender, eventArgs) => setResponsePage(...);
当然,也有一对夫妻带着这个缺点。首先,可以有多个点击处理程序,这可能不是很酷。 ,也不会强制实现者添加一个Click处理程序
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.
另一个选择可能是只是有一个封闭性是这样的:
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.
所以,我的问题是,你如何仿效地道的C#这样的事情?
So, my question is, how do you emulate something like this in idiomatic C#?
推荐答案
您可以委托是连接类的构造函数的一部分。这样,用户将不得不添加它。
You can make the delegate be part of the constructor of the Link class. This way the user will have to add it.
public class Link
{
public Link(string id, Action handleStuff)
{
...
}
}
然后创建一个实例是这样的:
Then you create an instance this way:
var link = new Link("id", () => do stuff);
这篇关于匿名内部类在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!