【发布时间】:2012-07-06 21:54:44
【问题描述】:
好的.. 我有一个非常尴尬的问题,我认为这与 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 存储为类中的私有字段。如果我尝试执行以下操作,现在在同一个班级但在不同的功能中:
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;
}
【问题讨论】:
-
如果您可以展示一个简短但完整的程序来演示问题,这将非常有帮助,最好是作为控制台应用程序。哦,看起来你有太多的字段来设计一个精心设计的结构。你有什么理由不把它作为一门课吗?
-
也提供
PointStruct结构。 -
我怀疑你误解了类和结构之间的区别。与是否需要方法无关。
-
你说
pointValues.Add没有在别处使用;pointValues[key] = ...是否在任何地方使用过? -
@SokwhanHuh 是的,但是上面的代码本身不应该失败无论是
class还是struct。所以:其他事情正在发生。事实仍然是,几乎可以肯定(嗯,不仅仅是“几乎”)不应该是struct。这无助于澄清。
标签: c# .net winforms string dictionary