Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

java - Anonymous inner classes in 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(...);
    }
};

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

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

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...