列表/属性的引用集合

Naw*_*waz 6 c# containers indexer properties list

考虑这些属性,

        double _temperature;
        public double Temperature
        {
            get { return _temperature; }
            set { _temperature = value; }
        }
        double _humidity;
        public double Humidity
        {
            get { return _humidity; }
            set { _humidity = value; }
        }
        bool _isRaining;
        public bool IsRaining
        {
            get { return _isRaining; }
            set { _isRaining = value; }
        }
Run Code Online (Sandbox Code Playgroud)

现在我想制作一个像这样的列表/集合/容器,

PropertyContainer.Add(Temperature);  //Line1
PropertyContainer.Add(Humidity);     //Line2
PropertyContainer.Add(IsRaining);    //Line3
Run Code Online (Sandbox Code Playgroud)

我想这样做,以后我可能能够使用索引访问属性的当前值,像这样,

object currentTemperature =  PropertyContainer[0];
object currentHumidity    =  PropertyContainer[1];
object currentIsRaining   =  PropertyContainer[2];
Run Code Online (Sandbox Code Playgroud)

但显然,这不会起作用,因为PropertyContainer[0]它将返回旧值 - Temperature添加Temperature到容器时的值(参见Line1上文).

有没有解决这个问题的方法?基本上我想统一访问属性的当前值; 唯一可以改变的是索引.然而,索引也可以是字符串.

PS:我不想使用Reflection!

Bot*_*000 11

好吧,你可以使用Lambdas:

List<Func<object>> PropertyAccessors = new List<Func<object>>();
PropertyAccessors.Add(() => this.Temperature);
PropertyAccessors.Add(() => this.Humidity);
PropertyAccessors.Add(() => this.IsRaining);
Run Code Online (Sandbox Code Playgroud)

那么你可以这样:

object currentTemperature = PropertyAccessors[0]();
Run Code Online (Sandbox Code Playgroud)