加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 列出/属性引用的集合

发布时间:2020-12-15 08:31:55 所属栏目:百科 来源:网络整理
导读:考虑这些属性, double _temperature; public double Temperature { get { return _temperature; } set { _temperature = value; } } double _humidity; public double Humidity { get { return _humidity; } set { _humidity = value; } } bool _isRaining;
考虑这些属性,
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; }
        }

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

PropertyContainer.Add(Temperature);  //Line1
PropertyContainer.Add(Humidity);     //Line2
PropertyContainer.Add(IsRaining);    //Line3

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

object currentTemperature =  PropertyContainer[0];
object currentHumidity    =  PropertyContainer[1];
object currentIsRaining   =  PropertyContainer[2];

但显然,这不会起作用,因为PropertyContainer [0]将返回旧值 – 温度在向容器添加温度时所具有的值(参见上面的Line1).

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

PS:我不想使用Reflection!

解决方法

好吧,你可以使用Lambdas:
List<Func<object>> PropertyAccessors = new List<Func<object>>();
PropertyAccessors.Add(() => this.Temperature);
PropertyAccessors.Add(() => this.Humidity);
PropertyAccessors.Add(() => this.IsRaining);

那么你可以这样:

object currentTemperature = PropertyAccessors[0]();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读