【问题标题】:java hashtable to c# dictionaryjava hashtable 到 c# 字典
【发布时间】:2014-09-26 14:00:08
【问题描述】:

Java 代码:

//BleDevice is a class
public Hashtable<String, BleDevice> meusBLEs = new Hashtable<String, BleDevice>();

//BleRequest is another class
BleRequest currentRequest = null;

//deviceAddress is a string from BleRequest
BleDevice ble=meusBLEs.get(currentRequest.deviceAddress);

我正在使用哈希表并将值设置为 BleDevice 变量;

现在我在 c# 中尝试做的是同样的事情,但使用的是 Dictionary:

public Dictionary<String, BleDevice> meusBLEs = new Dictionary<String, BleDevice>();

BleRequest currentRequest = null;

BleDevice ble = meusBLEs.get...//HERE'S IS WHAT I DON`T KNOW HOW TO DO. THE METHOD GET DON`T EXIST

我不能在c#中使用hashtable,因为我不能像java的hashtable那样设置参数。

【问题讨论】:

    标签: java c# dictionary xamarin hashtable


    【解决方案1】:
    BleDevice ble = meusBLEs[currentRequest.deviceAddress];
    

    【讨论】:

    • 仅供参考,与 Java 不同,如果字典中缺少请求的键,这种检索值的方法会引发异常。
    【解决方案2】:

    .NET 中的行为与 Java 略有不同;特别是,虽然 Java 的 get() 方法可能会针对缺失值返回 null,但这种约定不适用于值类型可能不是引用类型的 .NET。

    实际上有两种检索值的标准方法:

    BleDevice ble = meusBLEs[currentRequest.deviceAddress];
    

    如果字典中不存在键 currentRequest.deviceAddress 的值,上述语句将引发异常。或者,您可以使用TryGetValue 方法:

    BleDevice ble;
    /* bool found = */ meusBLEs.TryGetValue(currentRequest.deviceAddress, out ble);
    

    如果TryGetValue 返回false,则out 参数的值将是default(TValue)

    【讨论】:

    • 您可以使用以下扩展方法来准确重现 Java 行为: internal static TValue GetValueOrNull(this IDictionary dictionary, TKey key) { TValue ret; dictionary.TryGetValue(key, out ret);返回 ret; }
    【解决方案3】:

    只需这样做:BleDevice ble = meusBLEs[the_key_you_have]

    【讨论】:

      猜你喜欢
      • 2022-11-12
      • 2011-10-16
      • 2011-09-21
      • 2010-09-23
      • 1970-01-01
      • 2012-12-22
      • 2011-07-11
      • 2011-06-22
      • 1970-01-01
      相关资源
      最近更新 更多