我可以在重载的结构运算符中使用常量参数吗?
Can I use constant parameters in overloaded struct operators?
我可以在 .NET Core 2.0
class 库中定义以下不可变结构:
public struct S {
public readonly int v;
public S(int value) => v = value;
public static S operator +(in S l, in S r)
=> new S(l.v + r.v);
}
在第二个项目(.NET Core 2.0
控制台应用程序)中,我尝试使用重载运算符。因此,我添加了对库项目的项目引用。但是下面的代码编译失败:
class Program {
static void Main(string[] args)
=> Console.WriteLine((new S(4) + new S(3)).v);
}
错误信息:
Error CS0019: Operator '+' cannot be applied to operands of type 'S' and 'S'
详情:
- 我已将两个项目配置为使用最新的
C#
版本 (C# 7.2
)
- 使用
.NET CORE 2.0
作为目标框架
- 如果我在同一个项目中使用它,编译工作正常
- 如果我删除
l
和 r
的 in
修饰符,编译工作正常
- 使用
ref
修饰符 l
和 r
失败 ERROR CS0631
- 我的环境:VS 2017 15.5.5 社区
这是一个编译器错误,已在本期报告给团队:Use in-parameter operator from different assembly。看起来修复在 master 中,但我可以确认问题在 15.5.6 中仍然存在。
我可以在 .NET Core 2.0
class 库中定义以下不可变结构:
public struct S {
public readonly int v;
public S(int value) => v = value;
public static S operator +(in S l, in S r)
=> new S(l.v + r.v);
}
在第二个项目(.NET Core 2.0
控制台应用程序)中,我尝试使用重载运算符。因此,我添加了对库项目的项目引用。但是下面的代码编译失败:
class Program {
static void Main(string[] args)
=> Console.WriteLine((new S(4) + new S(3)).v);
}
错误信息:
Error CS0019: Operator '+' cannot be applied to operands of type 'S' and 'S'
详情:
- 我已将两个项目配置为使用最新的
C#
版本 (C# 7.2
) - 使用
.NET CORE 2.0
作为目标框架 - 如果我在同一个项目中使用它,编译工作正常
- 如果我删除
l
和r
的 - 使用
ref
修饰符l
和r
失败ERROR CS0631
- 我的环境:VS 2017 15.5.5 社区
in
修饰符,编译工作正常
这是一个编译器错误,已在本期报告给团队:Use in-parameter operator from different assembly。看起来修复在 master 中,但我可以确认问题在 15.5.6 中仍然存在。