c# - 带委托的隐式参数修饰符?(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);
现在在我的用例中,参数类型foo
和bar
可能有长名称、通用参数等。
类型信息已经存在于定义此委托类型的位置。有没有办法避免让我的用户显式键入此委托的参数?
我期望(foo, bar) =>
或(foo, in bar) =>
工作,但事实并非如此。
编辑:我玩得更多,这似乎也是如此ref
,我猜测所有参数修饰符。因此,问题名称从仅询问更改为in
一般修饰符
解决方案
不,您不能提供带有隐式匿名函数参数的修饰符。
如果您查看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
;
我同意这可能有点令人沮丧 - 但我不希望它很快改变。
推荐阅读
- node.js - Node.js Express Post 请求正文为空
- firebase - 如何使用颤振从 Firebase 实时数据库中检索特定数据?
- java - 如何将值保存到Edittext?
- teradata - 使用 Teradata 中增量表中的 MERGE/INSERT 将非重复项插入主表
- swiftui - SwiftUI井字棋盘
- installation - 安装 Expo-CLI 时出错 .. 甚至尝试过 npm install --unsafe-perm -g expo-cli 但没有奏效
- java - Java 8:AveragingDouble 和映射到对象
- asp.net-mvc - Aspnet API 控制器参数未正确反序列化
- reactjs - React 单元测试 const 箭头函数
- javascript - 不正确的日期格式 moment.js