C#中的委托使用隐式参数修饰符是什么?

7

我正在开发一个允许用户实例化某些委托的库。

我定义了一个委托类型,该类型处理结构体作为其参数之一,我们仅需要读取而不修改,因此in关键字似乎很有用。

public struct SomeStruct 
{ 
    public string x; 
    // and possibly more...
}

public delegate void MyDelegate(object foo, in SomeStruct bar);

然而,当我尝试创建时,它告诉我需要放置 in
// Parameter 2 must be declared with the 'in' keyword
MyDelegate x = (foo, bar) => System.Console.WriteLine(bar.x);

如果我使用in,现在必须显式地键入参数...

// doesn't work
MyDelegate x = (foo, in bar) => System.Console.WriteLine(bar.x);

但是现在我明确地输入了第二个参数,第一个参数也需要明确。

// Inconsistent lambda parameter usage; parameter types must be all explicit or all implicit
MyDelegate x = (foo, in SomeStruct bar) => System.Console.WriteLine(bar.x);

// ok
MyDelegate x = (object foo, in SomeStruct bar) => System.Console.WriteLine(bar.x);

在我的用例中,参数foobar的类型可能具有很长的名称、泛型参数等。

在定义此委托类型时已经有了类型信息。有没有办法避免让用户显式地为此委托键入参数?

我原以为(foo, bar) =>(foo, in bar) =>可以工作,但实际上不行。

编辑:我继续尝试并发现这对于ref也是一样的问题,我猜测其他所有参数修饰符也是如此。因此,问题的名称已经从仅询问in更改为普遍的修改器。

1个回答

2
不,您不能为隐式匿名函数参数提供修饰符。
如果您查看 ECMA 标准中的语法(目前适用于 C# 6,因此缺少“in”修饰符),您将会看到以下区别:explicit_anonymous_function_parameter 包括可选的修饰符和类型,而 implicit_anonymous_function_parameter 只是一个标识符。
explicit_anonymous_function_parameter
    : anonymous_function_parameter_modifier? type Identifier
    ;

anonymous_function_parameter_modifier
    : 'ref'
    | 'out'
    ;

implicit_anonymous_function_parameter
    : Identifier
    ;

我同意这可能会有点令人沮丧 - 但我不会期望它很快改变。

感谢回复。这真是太遗憾了,因为它使我正在尝试的API类型难以使用:/ 我有没有办法检查团队是否已经提出或讨论了这个问题? - James
@James:您可以在 https://github.com/dotnet/csharplang 上提出它。 - Jon Skeet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接