【问题标题】:dynamically naming a structure c#动态命名结构 c#
【发布时间】:2012-04-30 04:17:13
【问题描述】:

我正在编写的程序有许多结构,这些结构取决于许多因素,主要是我无法预测这些结构中有多少,所以程序自己创建它们。

结构看起来像这样;

public struct boardState
    {
        public int structid;
        public char[] state;
    }

如何让程序在没有我明确命名的情况下为这些结构命名?

理想情况下,会有一个名为 structNum 的 int 跟踪已创建的结构数量,然后将根据 structNum 的值命名任何新结构,但我不确定这是否可以完成,有没有办法或者你能推荐一个更好的方法?

谢谢。

【问题讨论】:

  • 你对值类型的理解是有缺陷的。

标签: c# dynamic struct naming


【解决方案1】:

如果您不知道要获得的值的确切数量,可以使用List<boardState>,它可以保存任意长数量的值。在运行时动态命名不是 .NET 的特性。编译后真的没有名字。

var theList = new List<boardState>();
// add
theList.Add(new new boardState());
// get one
int id = theList[0].structid;
// iterate
foreach(var s in theList)
    // do something
int cnt = theList.Count;

【讨论】:

  • 这似乎是最好的解决方案,但我不确定如何做到这一点。我试过这样; int x = lostList.Count;丢失列表.Add(x); lostList[x].state = sentstate;但这不起作用,我该怎么做?
【解决方案2】:

如果没有大量的反射,你不能在运行时做动态变量名。

最简单的解决方案是将结构保存在 List 或类似集合中:

List<boardState> boardStates = new List<boardState>();

【讨论】:

    猜你喜欢
    • 2016-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多