对口在C#中的匿名接口实现 [英] Counterpart to anonymous interface implementations in C#
问题描述
我的工作从Java翻译一些代码,C#,但我有一些麻烦,也许有人在那里可以帮助?
我有问题试图复制匿名。接口实现,被广泛应用于Java的,但不知道如何
一个例子是:
列表<数据>队列1 =新的ArrayList<数据>(集);
//排序的第一个提升的数据
Collections.sort(队列1,新的比较<距离;数据>(){
@覆盖
公众诠释比较(数据DATA1,DATA数据2){
双距离1 = distanceFunction.calculate(DATA1,promoted.first);
双距离2 = distanceFunction.calculate(数据2,promoted.first);
返回Double.compare(距离1,距离2);
}
});
我想问题复制被广泛采用在Java中
块引用>
这些都不是内联函数,这是实现特定接口的匿名类。内联函数p>
C#提供的代表的,你可以定义内嵌或在一个单独的功能。
下面是排序的一个例子的
列表<数据>使用
代替比较< T>
委托:列表<数据>队列=新的List<数据>();
queue.Sort(
(左,右)= GT; {
双距离1 = distanceFunction.Calculate(左,promoted.first);
双距离2 = distanceFunction.Calculate(没错,promoted.first);
返回Double.Compare(距离1,距离2);
}
);
请注意,为了使这项工作,在
distanceFunction
变量需要在范围在您调用queue.Sort
的地方。它可以调用点以上定义的局部变量,或者类封闭,使调用函数的成员变量/属性。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); } });
解决方案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 theComparison<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 invokequeue.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.这篇关于对口在C#中的匿名接口实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!