日期:2014-05-19  浏览次数:21334 次

List泛型Add后,所有值都是最后一次Add的结果。请高物帮忙,解决立即结帐
//程序如下
   
                public   struct   MyStructTest
                {
                        public   int   Flag;
                        public   Point   pt;
                        public   List <string>   aryMark
                  };
                List <MyStructTest>   aryTest   =   new   List <MyStructTest> ();

MyStructTest   test1;
test1.aryMark   =   new   List <string> ();
test1.aryMark.Add( " ");

for(int   i   =   0;   i   <   10;   i   +++
{
test1.Flag   =   i;
test1.pt   =   new   Point(i,i);
test1.aryMark[0]   =   i.ToString();

aryTest.Add(   test1   );

}

//错误结果
//最后得到的aryTest中,所有元素的aryMark[0]值都是9。本来我希望的是从0-9
//哪位高人给解决一下



------解决方案--------------------
for(int i = 0; i < 10; i +++
{
test1.Flag = i;
test1.pt = new Point(i,i);
test1.aryMark[0] = i.ToString();

aryTest.Add( test1 );

}

每次都在加同一个对象,感觉是
------解决方案--------------------
MyStructTest makeMyStruct()
{
MyStructTest test1;
test1.aryMark = new List <string> ();
test1.aryMark.Add( " ");
}

for(int i = 0; i < 10; i++)
{
MyStructTest test1 = makeMyStruct();
test1.Flag = i;
test1.pt = new Point(i,i);
test1.aryMark[0] = i.ToString();

aryTest.Add( test1 );

}

------解决方案--------------------
你有把数据从0存到9,但是最后是9把以前的覆盖了,设断点调试下
------解决方案--------------------
test1.aryMark[0] = i.ToString();
这里你每次都是将i放到数组[0]里啊,你的意思应该是写test1.aryMark[i]吧
------解决方案--------------------
楼主的意思是否是想这样:

public struct MyStructTest
{
public int Flag;
public Point pt;
public List <string> aryMark
};
List <MyStructTest> aryTest = new List <MyStructTest> ();

MyStructTest test1;
test1.aryMark = new List <string> ();
test1.aryMark.Add( " ");

for(int i = 0; i < 10; i +++
{
test1.Flag = i;
test1.pt = new Point(i,i);
test1.aryMark[i] = i.ToString();
}

aryTest.Add( test1 );
------解决方案--------------------
把一个对象添加了10次 当然得到10个相同的对象 就改为
static void Main(string[] args)
{
List <MyStructTest> aryTest = new List <MyStructTest> ();

for (int i = 0; i < 10; i++)
{
MyStructTest test1;
test1.aryMark = new List <string> ();
test1.aryMark.Add( " ");