java hashtable to c# dictionary

泄露秘密 提交于 2019-12-13 09:45:40

问题


Java code:

//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);

I'm using a hashtable and set the value to the BleDevice variable;

Now what I'm trying to do in c#, is the same thing but using 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

I can't use hashtable in c# cause I can't set the parameter like java's hashtable.


回答1:


BleDevice ble = meusBLEs[currentRequest.deviceAddress];



回答2:


The behavior is a bit different in .NET than Java; in particular, while the Java's get() method may return null for missing values, such a convention is not applicable in .NET where the value type may not be a reference type.

There are actually two standard ways to retrieve a value:

BleDevice ble = meusBLEs[currentRequest.deviceAddress];

The statement above will throw an exception if the value for key currentRequest.deviceAddress is not present in the dictionary. Alternatively, you can use the TryGetValue method:

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

If TryGetValue returns false, the value of the out parameter will be default(TValue).




回答3:


Just do this: BleDevice ble = meusBLEs[the_key_you_have].



来源:https://stackoverflow.com/questions/26061406/java-hashtable-to-c-sharp-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!