C#: Properties Map
Is there a PropertiesMap in C# which exposes methods like GetDouble(string), GetDateTime(string), etc..?
IDictionary<string,string>
f开发者_如何学JAVAorces users to take care of type conversion.
Yes there is ExpandoObject and it has a very clean syntax.
dynamic propertyMap = new ExpandoObject();
var item = propertyMap as IDictionary<String, object>;
item["A"] = DateTime.Now;
item["B"] = "New val 2";
propertyMap.C = 1234
Console.WriteLine(propertyMap.A);
Console.WriteLine(propertyMap.B);
Console.WriteLine(propertyMap.C);
You can use the Dictionary class and add extension methods for all data types that you wanr to have Get method, or add a generic Get method and use it:
public static class Extensions
{
public static T Get<T>(this Dictionary<string, object> dictionary, string key)
{
if (dictionary == null)
{
throw new ArgumentNullException("dictionary");
}
if (key == null)
{
throw new ArgumentNullException("key");
}
return (T)dictionary[key];
}
}
You even can create alias for the Dictionary<string, object>
type:
using PropertiesMap = System.Collections.Generic.Dictionary<string, object>;
And usage of this:
PropertiesMap pm = new PropertiesMap { { "1", 1 }, { "2", DateTime.Now }};
Console.WriteLine(pm.Get<int>("1"));
Console.WriteLine(pm.Get<DateTime>("2"));
You can use Convert
, it can handle a lot of the conversions you will need.
Convert.ToDateTime(string value) //about 7 overloads
Convert.ToInt32(string value)
Convert.ToDouble(string value)
It has a lot of options for conversions, with plenty of overloads.
Can you use Convert.ToXXX
? Not sure what your question has to do with IDictionary<string, string>
though...
See this MSDN page.
A Dictionary<string,object>
can store anything without conversion. However you will have to cast when retrieving the values:
var dict = new Dictionary<string,object>();
dict.Add("Name", "John");
dict.Add("Age", 20);
...
string name = (string)dict["Name"];
int age = (int)dict["Age"];
精彩评论