gpt4 book ai didi

c# - 在 C# 中为可空结构的成员赋值

转载 作者:太空宇宙 更新时间:2023-11-03 19:42:31 29 4
gpt4 key购买 nike

在 C# 中,我有一个这样的结构:

public struct Slab
{ public float[] sizeM;
public string textureSrc;
//more members, not relevant here...
}

还有一个像这样:

public struct Tombstone
{ public Slab mainSlab;
public Slab? basing;
//more...
}

现在,我要修改baseing的成员:

uiState[0].stone.basing.Value.sizeM[2] = Int32.Parse(breadthField.Value) / 100.0f;
uiState[0].stone.basing.Value.textureSrc = fileName;

(uiState[0].stoneTombstone 类型)

这两个调用中的第一个调用正常工作,因为我只是更改 basing 中的数组成员,而不是数组本身。然而,第二个提示:

Cannot modify the return value of 'Slab?.Value' because it is not a variable

如果我对不可为 null 的 mainSlab 执行相同操作,它会起作用。有没有一种方法可以在不将整个 base 复制到局部变量进行更改的情况下执行此操作?

最佳答案

Is there a way to do this without copying the whole basing to a local variable for changes?

不,因为Nullable<T>不提供对基础值字段的直接访问。您不能“就地”修改它。

当您使用可变结构时,会出现各种各样的小问题。我强烈建议您尽可能使用类或不可变结构,以避免这些极端情况。

关于c# - 在 C# 中为可空结构的成员赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51098690/

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