【问题标题】:Looping over the value inside property which is present inside the struct循环遍历结构内部存在的属性内部的值
【发布时间】:2020-03-30 12:10:05
【问题描述】:

我创建了一个结构,它具有一些属性,例如

public struct DeviceDetailModel
{
  public static readonly DeviceDetailModel DT851P = new DeviceDetailModel("851P","v1","v2");
  public static readonly DeviceDetailModel DT852P = new DeviceDetailModel("852P","v3","v4");
  public static readonly DeviceDetailModel DT83P = new DeviceDetailModel("853P","v5","v6");
  public static readonly DeviceDetailModel DT854P = new DeviceDetailModel("854P");


 public string DeviceName { get; private set; }
 public string Value1 { get; private set; }
 public string Value2 { get; private set; }

 private DeviceDetailModel(string deviceName,string value1,string value2)
 {
  DeviceName = deviceName;
  Value1 = value1;
  Value2 = value2;
 }
}

现在,如果我想获得单个项目的详细信息,我只需 DeviceDetailModel.DT854P

但问题是我会在运行时获得一个值,我必须使用它来确定我必须返回哪个结构属性

例如 = 我的运行时值是 853P 我想循环遍历我的结构来确定DeviceName 中的哪个位置与这个值853P 匹配,哪个应该返回DeviceDetailModel.DT83P

我能够遍历结构的属性,但无法获取值

编辑:根据我的运行时值,我需要迭代 DeviceName 的值,如果值匹配,它应该返回关联的属性

【问题讨论】:

  • 我不能 100% 确定我是否正确理解了这个问题,但也许使用字典而不是你的结构来解决问题?
  • 你能改写最后 5 行吗?它们根本无法理解。
  • @RolandDeschain 我在结构中有多个属性,所以键值对在这里对我不起作用
  • @Sheradil 我试图改写它
  • 但是你描述它的方式你可以使用DeviceName作为键和相应的类实例作为值,或者我在这里遗漏了什么?那么根本不需要循环,直接通过DeviceName访问字典项即可

标签: c# .net class c#-4.0 struct


【解决方案1】:

这是一个相当简单的选择:

public struct DeviceDetailModel
{
    private static readonly Dictionary<string, DeviceDetailModel> models = new Dictionary<string, DeviceDetailModel>
    {
        {"851P", new DeviceDetailModel("851P")},
        {"852P", new DeviceDetailModel("852P")},
        {"853P", new DeviceDetailModel("853P")},
        {"854P", new DeviceDetailModel("854P")},
    };

    public static DeviceDetailModel DT851P get => models["851P"];
    public static DeviceDetailModel DT852P get => models["852P"];
    public static DeviceDetailModel DT83P get => models["853P"];
    public static  DeviceDetailModel DT854P get => models["854P"];

    private DeviceDetailModel(string deviceName)
    {
        DeviceName = deviceName;
    }

    public string DeviceName {get;private set;}

    public DeviceDetailModel? FindByDeviceName(string deviceName)
    {
        return models.TryGetValue(deviceName, out var value) ? value : (DeviceDetailModel)null;
    }
}

请注意,FindByDeviceName 的返回值是 Nullable&lt;DeviceDetailModel&gt;,所以如果您正在寻找一个未找到的字符串,您不会得到异常,但 null

【讨论】:

  • 嗯,这几乎就是我试图在上面提出的观点......
猜你喜欢
  • 1970-01-01
  • 2020-08-20
  • 1970-01-01
  • 2015-02-02
  • 2020-03-30
  • 1970-01-01
  • 2013-02-03
  • 2017-05-12
  • 2020-03-01
相关资源
最近更新 更多