问题
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