【问题标题】:List/Collection of references to Properties对属性的引用列表/集合
【发布时间】:2011-05-28 03:38:21
【问题描述】:

考虑这些属性,

        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

我想这样做,以便稍后我可以使用 index 访问属性的 当前 值,类似这样,

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

但很明显,这是行不通的,因为PropertyContainer[0] 将返回旧值——Temperature 在将Temperature 添加到容器时所具有的值(参见上面的Line1)。

这个问题有什么解决办法吗?基本上我想访问 当前 属性的值 uniformly;唯一可以改变的是索引。然而,索引也可以是字符串。

PS:我不想使用反射!

【问题讨论】:

    标签: c# list properties containers indexer


    【解决方案1】:

    嗯,你可以使用 Lambda:

    List<Func<object>> PropertyAccessors = new List<Func<object>>();
    PropertyAccessors.Add(() => this.Temperature);
    PropertyAccessors.Add(() => this.Humidity);
    PropertyAccessors.Add(() => this.IsRaining);
    

    那么你可以这样做:

    object currentTemperature = PropertyAccessors[0]();
    

    【讨论】:

    • 这是很棒的解决方案。在我发布问题后,我从another topic 得到了相同的解决方案。非常感谢您对这个绝妙技巧的快速响应!
    • 糟糕,我忘记了。实际上,在它要求我等待 5 分钟之前,天知道为什么。无论如何,回答接受并从我那里 +1。
    猜你喜欢
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多