2016-11-03 54 views
-1

可以说我有类与大量的冗余特性,我想将它们存储在列表中,词典或任何改变对象的属性,而将其存储在列表

public class Foo 
{ 
public Bar Bar1 {get;set;} 
public Bar Bar2 {get;set;} 
public Bar Bar3 {get;set;} 
public Buzz Buzz1 {get;set;} 
public Buzz Buzz2 {get;set;} 
public Buzz Buzz3 {get;set;} 


public void UpdateObject(Buzz newValue) 
{ 
var dict = new List<KeyValuePair<Bar, Func<Buzz >>>() 
     { 
       new KeyValuePair<Bar, Func<Buzz>>(this.Bar1 ,()=>this.Buzz1), 
       new KeyValuePair<Bar, Func<Buzz>>(this.Bar2 ,() => this.Buzz2), 
       new KeyValuePair<Bar, Func<Buzz>>(this.Bar3 ,() => this.Buzz3) 
     }; 

foreach (var item in dict) 
     { 
      if (true) 
      { 
       var value = item.Value.Invoke(); 
       value = newValue; 
      } 
     } 
} 

} 

当然value的改变,但Foo的Buzz1/2/3财产不是。我如何存储对列表中的对象属性的某种引用,获取此项目并更改对象的值?

回答

2

而是用钥匙和一个二传手,存储密钥,一个getter和setter方法的键值对:

List<Tuple<Bar, Func<Buzz>, Action<Buzz>> 

Action<Buzz>是一个lambda是需要为Buzz一个新值作为参数。

var dict = new List<Tuple<Bar, Func<Buzz>, Action<Buzz>> 
    { 
     new Tuple<Bar, Func<Buzz>, Action<Buzz>(this.Bar1 ,()=>this.Buzz1, x => this.Buzz1 = x), 
     // ...etc... 
    }; 

不知道你为什么这样做,但那会奏效。

如果是我,而不是TupleKeyValuePair,我会写一个ThingReference<T>类,带有两个lambda表达式,并存储那些在Dictionary<Bar, ThingReference<Buzz>>

相关问题