Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - Counterpart to anonymous interface implementations in C#

I'm working on translating some code from Java to C# but am having some trouble, maybe someone out there can help?

I have problems trying to replicate anonymous interface implementations that are widely used in Java, but have no idea how to.

An example is:

List<DATA> queue1 = new ArrayList<DATA>(dataSet);
            // Sort by distance to the first promoted data
            Collections.sort(queue1, new Comparator<DATA>() {
                @Override
                public int compare(DATA data1, DATA data2) {
                    double distance1 = distanceFunction.calculate(data1, promoted.first);
                    double distance2 = distanceFunction.calculate(data2, promoted.first);
                    return Double.compare(distance1, distance2);
                }
            });
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I have problems trying to replicate the inline functions that are widely used in Java

These are not inline functions, that's anonymous classes implementing a specific interface.

C# provides delegates that you can define inline or in a separate function.

Here is an example of sorting a List<DATA> in place using the Comparison<T> delegate:

List<DATA> queue = new List<DATA>();
queue.Sort(
    (left, right) => {
        double distance1 = distanceFunction.Calculate(left, promoted.first);
        double distance2 = distanceFunction.Calculate(right, promoted.first);
        return Double.Compare(distance1, distance2);
    }
);

Note that in order for this to work, the distanceFunction variable needs to be in scope at the spot where you invoke queue.Sort. It can be a local variable defined above the invocation point, or a member variable/property of the class enclosing the function that makes the call.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...