好的..我有一个非常尴尬的问题,我认为它与 C# 处理值类型与引用类型的方式有关,但我不确定这个错误到底是什么。
public partial class LogicSimulationViewerForm : Form
{
private Dictionary<string, PointStruct> pointValues;
private void SearchPoint(string code)
{
ReadDefaultPointValuesResponse result = ddcdao.ReadDefaultPoint(points);
pointValues = new Dictionary<string, PointStruct>();
for (int j = 0; j < result.pointidentifier.Length; j++)
{
if (!pointValues.ContainsKey(result.pointidentifier[j]))
{
PointStruct ps = new PointStruct();
ps.name = "Random String";
ps.pointidentifier = result.pointidentifier[j];
ps.outofservice = result.outofservice[j];
pointValues.Add(result.pointidentifier[j], ps);
...
pointValues 存储为类中的私有(private)字段。现在在同一个类中但在不同的函数中,如果我尝试执行以下操作:
PointStruct ps = pointValues[s];
MessageBox.Show(ps.name);
MessageBox.Show(ps.pointidentifier);
MessageBox.Show(ps.outofservice);
ps.pointidentifier 和 ps.outofservice 显示正确,但无论我做什么,ps.name 总是返回 null。我该如何解决这个问题?
编辑:根据要求,我添加了更多代码以进一步说明问题:
public struct PointStruct
{
public string pointidentifier;
public string affect;
public string outofservice;
public string priorityarray;
public string pointtype;
public string alarmstate;
public string correctvalue;
public string presentvalue;
public string name;
public string test;
}
最佳答案
只要没有巫术(显式字段布局、属性间接等),就绝对没有理由删除字段自身,无论它是 class
还是 结构
。
如果它是一个类
,我们也许可以将其归因于其他地方的粗心更新,即
var foo = pointValues[key];
// snip 2000 lines
foo.name = newValue; // which happens to be null
这当然会更新与字典引用的对象相同的基本对象。但是这不适用于struct
,因为副本是分开的(除非直接在数组中更新)。
鉴于您声明 pointValues.Add(...)
仅在一个地方使用,我能看到的导致这种情况的唯一方法是您通过索引器在其他地方覆盖它:
pointValues[key] = newValueWithANullName;
尽管如此;除非您有一些非常具体的原因,否则将 PointStruct
用作 struct
的目的很少。在我看来,它应该是一个类
。对于 struct
来说,它非常“胖”。还;在大多数情况下,struct
应该是不可变的。
关于C# 字符串从结构中消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11362211/