2017-07-27 49 views
0

我正在寻找一种方法来创建一个接受多个类作为值的字典。C#字典多个类作为值

我从小米网关和各种设备中获得价值,我已经为每种设备上课了。

例如我的磁传感器:

[XiaomiEquipement("magnet")] 
public class Magnet 
{ 
    public string Model { get; set; } = "magnet"; 
    public string Sid { get; set; } 
    public string Battery { get; set; } = "CR1632"; 
    public int BatteryLevel { get; set; } 
    public MagnetReport Report { get; set; } 
} 

[XiaomiEquipement("magnet_report")] 
public class MagnetReport 
{ 
    public int Voltage { get; set; } 
    public status { get; set; } 
} 

而且我wallplug:

[XiaomiEquipement("plug")] 
public class Plug 
{ 
    public string Model { get; set; } = "plug"; 
    public string Sid { get; set; } 
    public string Battery { get; set; } = "CR2450"; 
    public int BatteryLevel { get; set; } 
    public PlugReport Report { get; set; } 
} 

[XiaomiEquipement("plug_report")] 
public class PlugReport 
{ 
    public int Voltage { get; set; } 
    public string Status { get; set; }  
} 

小蜜网关发送两个类型的数据,报告时,事情发生心跳每x分钟。

{ “CMD”: “心跳”, “模型”: “插头”, “SID”: “158d000123f0c9”, “short_id”:11119 “数据”: “{\” 电压\“:3600 ,\ “状态\”:\ “关\”,\ “INUSE \”:\ “0 \”,\ “power_consumed \”:\ “7 \”,\ “load_power \”:\ “0.00 \”}” }

{“cmd”:“report”,“model”:“plug”,“sid”:“158d000123f0c9”,“short_id”:11119,“data”:“{\”status \“:\” “}”}

正如你所看到的,这两条线的数据并不相同。因此,我想在启动插件类时,在心跳或报告到达时填写缺失的数据。

我使用Activator.CreateInstance与传感器类型来创建正确的类。

modelType = Assembly.GetExecutingAssembly().GetTypes().SingleOrDefault(t => t.GetCustomAttribute<Response.XiaomiEquipementAttribute>()?.Model == read.Model); 
modelReportType = Assembly.GetExecutingAssembly().GetTypes().SingleOrDefault(t => t.GetCustomAttribute<Response.XiaomiEquipementAttribute>()?.Model == read.Model + "_report"); 

我尝试使用字典存储,然后我的传感器数据来编辑连接心跳后,而且是每一个传感器具有不同的类这是行不通的。

我尝试添加一个接口,它的工作,但它不适用于报告类。

如何将这些类包含到我的字典中并访问它?

基本上我想通过键搜索字典,获取价值并改变它的一部分。

+0

您是否尝试过使用抽象类? – noone392

+0

还是一个界面? –

+2

此外,如果你想它是任何你可以只是使值类型的对象,然后当确定什么类型时,只是调用object.type()并检查 – noone392

回答

1

您可以使用Dictionary<string, object>来存储它们。

var items = new Dictionary<string, object>(); 
var mag = new Magnet() { Sid = "1" }; 
var mot = new Motion() { Sid = "2" }; 
items.Add(mag.Sid, new Magnet()); 
items.Add(mot.Sid, new Motion()); 

然后你就可以使用确定像Object.GetType()这样类型:

foreach (var thisItem in items) 
{ 
    // or use thisItem.Value is Magnet 
    if (thisItem.Value.GetType().Name == "Magnet") 
    { 
     Console.WriteLine("Magnet"); 
    } 
    else 
    { 
     Console.WriteLine("Motion"); 
    } 
} 

你也可以把公共属性成一个基类,从基类继承两个类。

+0

基类的好名字是* Sensor *:o) –

+1

我会'如果(thisItem.Value是磁铁磁铁)' –

+0

@KrisVandermotten谢谢!这是一个很好的建议。其实它更好。 – CodingYoshi