为现有c#添加新属性



当两个'if'条件都满足时,我希望将Start与值和时间一起添加到相同的DataList中。

public List<object> DataList = new List<object>();
if(somecondition)
{     
DataList.Add(new { Value = Value, Time = time}); // assume this is DataList[0]
//var start = null;
//DataList.Add(new { Value = Value, Time = time, Start = start}); 
}
if(somecondition)  
{
-> how do I add `start` to DataList[0] here.
//DataList.Add(new { Start = start });
//DataList[0]?.Start  = start;   
}

之后,当我使用DataList时,它应该包含两个if条件的值。谢谢你。

这里有两个选项。

使用继承:

void Method()
{
/* init variables */
if (someCondition)
{
DataList.Add(new Data() { Value = Value, Time = time });
}
else if (someOtherCondition)
{
DataList.Add(new DataWithStart() { Value = Value, Time = time, Start = start });
}
}
public List<Data> DataList = new List<Data>();
public class Data
{
public string Value;
public string Time;
}
public class DataWithStart : Data
{
public string Start;
}

或者,使用ExpandoObject:

void Method()
{
/* init variables */
dynamic data = new System.Dynamic.ExpandoObject();
if (someCondition)
{
data.Value = Value;
data.Time = time;
}

if (someOtherCondition)
{
data.Start = start;
}

DataList.Add(data);
}
public List<System.Dynamic.ExpandoObject> DataList = new List<System.Dynamic.ExpandoObject>();
using System.Collections.Generic;
using System.Dynamic;
List<dynamic> DataList = new List<dynamic>();
dynamic data1 = new ExpandoObject();
if (someCondition)
{
data1.Value = Value;
data1.Time = time;
}
if (someCondition)
{
data1.Start = start;
}
DataList.Add(data1);

你可以用ExpandoObject以最简单的方式解决。

相关内容

  • 没有找到相关文章

最新更新