动态分配字段

Dar*_*der 1 .net c# reflection collections

我有如下属性集:

public string Foo1 {set;get;}
public string Foo2 {set;get;}
public string Foo3 {set;get;}
public string Foo4 {set;get;}
public string Foo5 {set;get;}
public string Foo6 {set;get;}
public string Foo7 {set;get;}
public string Foo8 {set;get;}
public string Foo9 {set;get;}
......
public string Foo50 {set;get;}
Run Code Online (Sandbox Code Playgroud)

然后我迭代一个集合,如下所示:

foreach(var element in sortedCollection.Keys){
   if(element != null)
   // in this block I would like to assign the element to the properties above
   // ex:
   foo?? = sortedCollection[element];
   // ?? need to be replaced by index.
}
Run Code Online (Sandbox Code Playgroud)

是否有捷径可寻?

Mat*_*ott 5

我认为更好的设计是:

public List<string> Foos { get; private set; }
Run Code Online (Sandbox Code Playgroud)

如果你不能改变它,你可能会做类似的事情:

var type = typeof(MyCalss);
int index = 1;
foreach (var key in sortedCollection.Keys)
{
   var value = sortedCollection[key];
   var prop = type.GetProperty("Foo" + index);
   if (prop != null) prop.SetValue(this, value, null);

   index++;
}
Run Code Online (Sandbox Code Playgroud)

...当然还有一些错误处理,并this假设这是您班级中的一种方法.你能根据你的价值确定一个指数sortedCollection吗?

  • @ user177883:你应该抗议那些说你无法改进设计的人 - 修复这样糟糕的设计几乎总是更早做而不是更晚. (5认同)