gpt4 book ai didi

c# - 你可以在 c# 中的只读结构上设置默认参数吗?

转载 作者:行者123 更新时间:2023-12-03 17:06:10 26 4
gpt4 key购买 nike

似乎默认参数不适用于 c# 中的只读结构。我误解了什么吗?

   public readonly struct ReadonlyStruct
{
public ReadonlyStruct(int p1 = 1, byte p2 = 2, bool p3 = true)
{
P1 = p1;
P2 = p2;
P3 = p3;
}

public int P1 { get; }
public byte P2 { get; }
public bool P3 { get; }
}
使用 var test = new ReadonlyStruct(); 实例化此结构的实例似乎不遵守默认值。我究竟做错了什么?

最佳答案

与直觉相反,您不能在 struct 上拥有所有默认参数或显式无参数构造函数。 ,这不限于 readonly struct .
与类不同,一个 struct是值类型并且不需要构造函数,所以在你的情况下你根本不提供任何参数,因此构造函数永远不会被调用。
如文档中所述
结构类型设计的限制

When you design a structure type, you have the same capabilities aswith a class type, with the following exceptions:

You can't declare a parameterless constructor. Every structure typealready provides an implicit parameterless constructor that producesthe default value of the type.


当你不提供参数时,生成的 IL 会调用
OpCodes.Initobj Field

Initializes each field of the value type at a specified address to anull reference or a 0 of the appropriate primitive type.


此外

Unlike Newobj, initobj does not call the constructor method. Initobjis intended for initializing value types, while newobj is used toallocate and initialize objects.


相反,在下面的情况下它会。默认值将按照您期望的方式初始化。
var asd = new ReadonlyStruct(2);
以下生成的 IL 将是
newobj instance void ReadonlyStruct::.ctor(int32, uint8, bool)
OpCodes.Newobj Field

The newobj instruction allocates a new instance of the classassociated with ctor and initializes all the fields in the newinstance to 0 (of the proper type) or null references as appropriate.It then calls the constructor ctor with the given arguments along withthe newly created instance. After the constructor has been called, thenow initialized object reference (type O) is pushed on the stack.


简而言之,您可能需要重新考虑您的问题或使用静态创建方法。

关于c# - 你可以在 c# 中的只读结构上设置默认参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62527746/

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