1

假设我有这样的课程:

public class Config {
   public byte ALS { get; set; }
   public bool BCP { get; set; }
   public short NRG { get; set; }
   // 46 more bytes, shorts, and bools
   public byte GRT { get; set; }
}
Config myConfig = new Config();

现在假设我有一个定义了相同类的 Arduino,它通过串行(使用 /n 字符,所以我可以使用 SerialPort.ReadLine())以相同的顺序一次将每个道具值作为字符串发送给我。当每个值到达时,我想把它放在下一个属性中。我真的很想做这样的事情:

<psudo code>
for (int i = 0; i < 50; i++)
{
    myConfig[i] = (Config[i].GetType())port.ReadLine();  //reference the property by index, not by name
}
</psudo code>

请注意,在将新到达的值转换为适合目标属性类型之后,我将每个新到达的值放在实例的下一个属性中。我不是按名称(ALS、BCP.NRG 等)而是按索引(0、1、2、3 等)指定下一个属性。

有没有办法做到这一点?

戴夫

4

3 回答 3

2

您可以使用以下内容...

public class Config {
   [Display(Order=0)]
   public byte ALS { get; set; }

   [Display(Order=1)]
   public bool BCP { get; set; }

   [Display(Order=2)]
   public short NRG { get; set; }

   [Display(Order=3)]
   public byte GRT { get; set; }
}

该属性Display来自System.ComponentModel.DataAnnotations命名空间

现在您可以编写如下扩展方法

public static PropertyInfo GetProperty(this Type type, int index)
{
      return type.GetProperties().FirstOrDefault(p => ((DisplayAttribute)p.GetCustomAttributes(typeof(DisplayAttribute), false)[0]).Order == index);
}

现在您可以使用它并将值分配给对象上的字段,如下所示

Config config = new Config();
for(int i = 0; i < 50; i++)
{
     config.GetType().GetProperty(i).SetValue(config, port.ReadLine());
}
于 2013-08-07T05:51:14.123 回答
2

我可以想到几种解决方案,每种都有其优缺点(排名不分先后)

  1. 使用几个数组来存储你的变量和一个类型数组来知道把你得到的第 n 个结果放在哪里。

  2. 使用反射获取所有相关属性并修改它们。但是 - 得到它们一次并存储它们,不要每次都得到它们。并且不要依赖于订单 ( http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx ) - 创建您自己的订单属性并标记您的属性。因此,当您选择的订单在您重命名或删除属性时(或当 MS 更改 .net 时)不会改变。

  3. 使用对象数组来存储您的数据,但使用正确的类型从字符串中解析每个对象。然后,您可以让您的属性包装数组。

    公共字节 ALS
    {
    获取
    {
    返回 (字节)m_properties[ALS_INDEX];
    }
    设置
    {
    m_properties[ALS_INDEX] = 值;
    }
    }

于 2013-08-07T05:34:27.297 回答
0

您可以使用反射来迭代属性,这不会为您提供索引访问,但我认为属性以确定的顺序返回。

Type type = obj.GetType();
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = type.GetProperties(flags);

foreach (PropertyInfo property in properties)
{
    Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(obj, null));
}
于 2013-08-07T05:12:03.293 回答