开发者

List<dynamic>().Add problem C#

When I loop into the List, I always see the same value for all the items in the list.

Where am I going wrong?

here is what i did.

var DyObjectsList = new List<dynamic>; 
dynamic DyObj = new ExpandoObject(); 
if (condition1)
 { DyObj.Required = true;
   DyObj.Message = "Message 1开发者_如何学Python"; 
   DyObjectsList.Add(DyObj); } 
if (condition2)
 { DyObj.Required = false;
   DyObj.Message = "Message 2"; 
   DyObjectsList.Add(DyObj); 
 }

......

interestingly all the items in DyObjectsList are replaced with the values of the last assigned object.


You need to instantiate a new instance inside the body of the if statements (otherwise you are repeatedly modifying/adding a reference to the same instance):

if (condition1) { 
    dynamic DyObj = new ExpandoObject(); 
    DyObj.Required = true;
    DyObj.Message = "Message 1"; 
    DyObjectsList.Add(DyObj); } 
if (condition2) {
    dynamic DyObj = new ExpandoObject(); 
    DyObj.Required = false;
    DyObj.Message = "Message 2"; 
    DyObjectsList.Add(DyObj); 
}

Of course, even better is:

if(condition1) {
    dynamic obj = GetNewDynamicObject(false, "Message 1");
    DyObjectsList.Add(obj);
}
if(condition2) {
    dynamic obj = GetNewDynamicObject(true, "Message 2");
    DyObjectsList.Add(obj);
}

where the definition of GetNewDynamicObject is obvious.


You're adding the same object twice, and changing its properties in the middle.

You need to add a new ExpandoObject() every time.


When both conditions are true, then the variables will be set as in the last if block. You should probably use else if instead of second if block.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜