我可以在 .NET Core 2.0
类库中定义以下不可变结构:
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
修饰符,编译就会工作 - 对
l
和r
使用ref
修饰符失败,返回ERROR CS0631
- 我的环境:VS 2017 15.5.5 Community
最佳答案
这是一个编译器错误,已在本期报告给团队:Use in-parameter operator from different assembly .看起来修复在 master 中,但我可以确认问题在 15.5.6 中仍然存在。
关于c# - 我可以在重载的结构运算符中使用常量参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48795360/