[Java To C#] @FunctionalInterface 和 delegate

在把 Mojang 的 Brigadier 抄到 C# 上的时候遇到了一个问题:有个类 RedirectModifier 是一个 @FunctionalInterface,也就是可以使用 Lambda 表达式来代替构造匿名类的东西。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Copyright (c) Microsoft Croporation. All rights reserved.
// Licensed under the MIT license.

package com.mojang.brigadier;

import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;

import java.util.Collection;

@FunctionalInterface
public interface RedirectModifier<S> {
Collection<S> apply(CommandContext<S> context) throws CommandSyntaxException;
}

我们可以使用类似下面的方法来构造这个 Interface 的实例。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class TestInstantiateInterface {

@Test
public testInstantiateInterface() {

RedirectModifier<Object> byLambda = (context) => new ArrayList<Object>();

RedirectModifier<Object> byAnonymous = new RedirectModifier() {
@Override
Collection<Object> apply(CommandContext<Object> context) throws CommandSyntaxException {
return new ArrayList<S>();
}
}
}
}

但是 C# 里面明显没有这样的操作,当我以为要用别的方法的时候,我发现了 Comparison 的定义。

1
2
3
4
5
6
7
8
9
10
11
12
#nullable enable
namespace System
{
/// <summary>Represents the method that compares two objects of the same type.</summary>
/// <param name="x">The first object to compare.</param>
/// <param name="y">The second object to compare.</param>
/// <typeparam name="T">The type of the objects to compare.</typeparam>
/// <returns>A signed integer that indicates the relative values of <paramref name="x" /> and <paramref name="y" />, as shown in the following table.
///
/// <list type="table"><listheader><term> Value</term><description> Meaning</description></listheader><item><term> Less than 0</term><description><paramref name="x" /> is less than <paramref name="y" />.</description></item><item><term> 0</term><description><paramref name="x" /> equals <paramref name="y" />.</description></item><item><term> Greater than 0</term><description><paramref name="x" /> is greater than <paramref name="y" />.</description></item></list></returns>
public delegate int Comparison<in T>(T x, T y);
}

非常简单的一个 delegate,直接让我明白了 FunctionalInterface 在 C# 里是如何存在的。

所以我们可以把 RedirectModifier 在 C# 里定义成这样:

1
public delegate IEnumerable<TSource> RedirectModifier<TSource>(CommandContext<TSource> context);

一样简单的语句。