gpt4 book ai didi

c# - 为什么 ValueTuple 不能是常量?

转载 作者:太空狗 更新时间:2023-10-30 01:12:45 27 4
gpt4 key购买 nike

声明为字段的 ValueTuple 类型可以是可变的:

class Foo {
(int, int) bar = (0, 1);
}

或只读:

class Foo {
readonly (int, int) bar = (0, 1);
}

并且这种 (im) 可变性适用于每个成员。我希望它也可以扩展为 const 声明:

class Foo {
const (int, int) bar = (0, 1);
}

但是这个语句不编译。是否存在某些情况下它是不受欢迎的功能,或者它只是未实现的功能?

编辑好的我现在明白了。我的问题是基于 C# 编译器对待 ValueTuples 不同于其他类型的假设,关于关键字 readonly。所以,如果它已经是一个异常,为什么不为 consts 做另一个异常。但是,事实上,这个逻辑似乎适用于所有结构。所以这是行不通的:

class Foo {
readonly ExampleStruct field;
void Method() {
field.structField = 2;
}
}
struct ExampleStruct {
public int structField;
}

最佳答案

有一组有限的类型,可以在 c# 中用作常量 (more detailed here)。

Value tuple根本不在其中。

关于c# - 为什么 ValueTuple 不能是常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55786366/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com