问题
I am trying to use someone else's C# classes in my Windows 7 Phone app. The classes use objects of type Hashtable.
The file in question has
using System.Collections;
at the top, so I'm assuming that's the Hashtable object it wants.
When I try to build my solution, I get errors that the type or namespace name 'Hashtable' could not be found, are you missing a using directive or assembly reference.
In Microsoft's documentation of Hashtable, I see it says Assembly: mscorlib
But if I try to add mscorlib via Project>Add Reference, VS says it can't add it because it is automatically referenced by the build system.
What am I missing?
回答1:
The non-generic collections, including ArrayList
and HashTable
, are not included in Silverlight.
These classes are hold-overs from .Net 1.0 (which didn't have generics) and should not be used in new code.
Instead, you should use the generic collections—List<T>
and Dictionary<TKey, TValue>
.
回答2:
You have a few options:
Change your import to
using System.Collections.Generic;
and change every use of aHashTable
toDictionary<>
andArrayList
toList<>
.You might be able to get away with:
using HashTable = System.Collections.Generic.Dictionary<object, object>;
using ArrayList = System.Collections.Generic.List<object>;
Note that any future maintainer will hate you for doing this.But it's better to refactor the code to use the generic collections properly.
Create a class
Hashtable
in a namespaceSystem.Collections
, implementIDictionary<object, object>
by forwarding everything to an innerDictionary<object, object>
and implement the necessary changes in behavior (locking, missing keys, etc.); Create anArrayList
by encapsulationList<object>
. (suggested by henon)
回答3:
There are different mscorlibs depending on which .NET framework you are using. If you look in the "Other Versions" dropdown on the MSDN page, you will see Hashtable
is not a part of Silverlight. You will need to use a Dictionary<Object, Object>
(or ideally more strongly typed keys and value types)
回答4:
System.Collection is a legacy of first version of .Net - no generic types.
To fix your code use Dictorany class which is a hashtable at heart, and List insted of ArrayList.
回答5:
It worked for me changing:
Hashtable for Dictionary<object, object>
NameValueCollection for Dictionary<object, object>
Other problem I encoutered is Encoding.ASCII is not defined either, I sorted that with a function a stackoverflow lad wrote:
public static byte[] StringToAscii(string s) {
byte[] retval = new byte[s.Length];
for (int ix = 0; ix < s.Length; ++ix) {
char ch = s[ix];
if (ch <= 0x7f) retval[ix] = (byte)ch;
else retval[ix] = (byte)'?';
}
return retval;
}
credits here:
ASCIIEncoding In Windows Phone 7
So finally to return the ASCII this is what to do:
return StringToAscii(Encoding.Unicode.GetString(result.ToArray()));
来源:https://stackoverflow.com/questions/5011149/need-hashtable-and-arraylist