我在将 Java 代码移植到 C# 时遇到了这段代码。我不知道如何移植它,因为它似乎声明了类数组。我对 C# 的了解太有限,无法弄清楚如何在 C# 中实现此操作。在 C# 中是否有与此 Stub 声明等效的声明,它看起来会是什么样子?我将它缩小到最小,因为它声明了 10 个对象。代码如下所示:
public interface IcodecWeightFunctionStub
{
void hcodec_weight_func(int[] block, int block_offset, int stride, int log2_denom, int weight, int offset);
}
public interface IHcodecBiWeightFunctionStub
{
void hcodec_biweight_func(int[] dst, int dst_offset, int[] src, int src_offset, int stride, int log2_denom, int weightd, int weights, int offset);
}
public IHcodecWeightFunctionStub[] weight_hcodec_pixels_tab = new IHcodecWeightFunctionStub[] {
new IHcodecWeightFunctionStub() {
public void hcodec_weight_func(int []block, int block_offset, int stride, int log2_denom, int weight, int offset) {
weight_hcodec_pixels_c(16, 16, block, block_offset, stride, log2_denom, weight, offset);
}
},
new IHcodecWeightFunctionStub() {
public void hcodec_weight_func(int []block, int block_offset, int stride, int log2_denom, int weight, int offset) {
weight_hcodec_pixels_c(16, 8, block, block_offset, stride, log2_denom, weight, offset);
}
}
};
问题不在于在 C# 中实例化接口(interface),而在于在 C# 中返回新类。
请您参考如下方法:
C#的匿名委托(delegate)实现和lambdas最接近Java的匿名接口(interface)实现,但是接口(interface)需要有一个单一的方法。您的两个接口(interface)都有一个方法,因此您的代码可以按如下方式转换为 C#:
public delegate void HcodecWeightDelegate(int[] block, int block_offset, int stride, int log2_denom, int weight, int offset);
public delegate void HcodecBiweightDelegate(int[] dst, int dst_offset, int[] src, int src_offset, int stride, int log2_denom, int weightd, int weights, int offset);
public HcodecBiweightDelegate[] WeightHcodecPixelsTab = new HcodecBiweightDelegate[] {
(block, block_offset, stride, log2_denom, weight, offset) => {
weight_hcodec_pixels_c(16, 16, block, block_offset, stride, log2_denom, weight, offset);
}
, (block, block_offset, stride, log2_denom, weight, offset) => {
weight_hcodec_pixels_c(16, 8, block, block_offset, stride, log2_denom, weight, offset);
}
};
请注意,调用委托(delegate)也是不同的:在 Java 中,您可以这样调用它们:
weight_hcodec_pixels_tab[i].hcodec_weight_func(block, block_offset, stride, log2_denom, weight, offset);
在 C# 中,您没有方法名称(因为委托(delegate)封装了单个方法),所以相同的调用看起来像这样:
HcodecBiweightDelegate[i](block, block_offset, stride, log2_denom, weight, offset);
