首页 > 解决方案 > 带委托的隐式参数修饰符?(C#)

问题描述

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

我定义了一个委托类型,将结构作为其参数之一处理,我们只需要读取而不需要修改,因此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一般修饰符

标签: c#

解决方案


不,您不能提供带有隐式匿名函数参数的修饰符。

如果您查看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
    ;

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


推荐阅读