通过对象中的属性名称递增

时间:2018-10-30 11:30:48

标签: c# xamarin

我有以下对象:

namespace BluetoothExample
{
    public class Assay
    {
        public double Band_1 //Vis450
        {
            get;
            set;
        }
        public double Band_2 //Vis500
        {
            get;
            set;
        }
        public double Band_3 //Vis550
        {
            get;
            set;
        }
        public double Band_4 //Vis570
        {
            get;
            set;
        }
    }
}

我想填充对象中的4个带。我目前通过以下方式进行操作:

public Populate()
{
    int _i = 0;
    double[] nirData = new double[4];
        MyDevice.Characteristic.ValueUpdated += (sender, e) =>
        {
            nirData[_i] = BitConverter.ToDouble(e.Characteristic.Value, 0);
            _i++;
        };
    Assay assay = new Assay();
    assay.Band_1 = nirData[0];
    assay.Band_2 = nirData[1];
    assay.Band_3 = nirData[2];
    assay.Band_4 = nirData[3];
}

我想知道是否有可能在MyDevice.Characteristic.ValueUpdate方法内完成全部操作?我的想法是应该可以像这样增加和填充对象的属性:

string name = "assay.Band_" + _i;
name = BitConverter.ToDouble(e.Characteristic.Value, 0);

这显然是错误的,但是某种程度上证明了我的想法。

1 个答案:

答案 0 :(得分:0)

只需将您的乐队设为Array或List:

public class Assay
{
     public double[] Band 
     {
          get;
          set;
     }
}

然后您可以像这样简单地分配它:

public Populate()
{
    int _i = 0;
    double[] nirData = new double[4];
        MyDevice.Characteristic.ValueUpdated += (sender, e) =>
        {
            nirData[_i] = BitConverter.ToDouble(e.Characteristic.Value, 0);
            _i++;
        };
    Assay assay = new Assay();
    assay.Band = nirData;
}