是否有任何优雅的快速方法将对象映射到字典,反之亦然?
IDictionary<string,object> a = new Dictionary<string,object>();
a["Id"]=1;
a["Name"]="Ahmad";
// .....
Run Code Online (Sandbox Code Playgroud)
变
SomeClass b = new SomeClass();
b.Id=1;
b.Name="Ahmad";
// ..........
Run Code Online (Sandbox Code Playgroud) 如何将动态对象转换为Dictionary<TKey, TValue>C#我该怎么办?
public static void MyMethod(object obj)
{
if (typeof(IDictionary).IsAssignableFrom(obj.GetType()))
{
// My object is a dictionary, casting the object:
// (Dictionary<string, string>) obj;
// causes error ...
}
else
{
// My object is not a dictionary
}
}
Run Code Online (Sandbox Code Playgroud) 我目前正在使用json.net!我知道如何反序列化json数据以及如何映射我们的类.现在我渴望一些疑问!
假设我的jsonstrings是
"attributes":{
"color":"Brown",
"condition":"Used",
"currency":"USD",
"price":"10500",
"price_display":"$10,500",
}
Run Code Online (Sandbox Code Playgroud)
和我的属性类(我想在其上反序列化字符串)是
Public class Attribute
{
public string name{ get; set; }
public string value{ get; set; }
}
Run Code Online (Sandbox Code Playgroud)
现在我使用以下代码进行反序列化.
JavaScriptSerializer ser = new JavaScriptSerializer();
<classname> p = ser.Deserialize<classname>(jsonString);
Run Code Online (Sandbox Code Playgroud)
显然,这段代码根本不适用于上面的jsonstring.
现在如何在一个类中绑定这些名称值对?这可能吗 ?
将来,属性可能超过10但格式将与名称值对相同
我正在尝试使用 .NET 4.0 中的 System.Runtime.Caching.MemoryCache 类。我有一个通用的方法,因此我可以将任何类型传递到内存缓存中,并在调用时将其取回。
该方法返回一个 object 类型的对象,该对象是具有包含缓存对象的字段 Value 的匿名类型。
我的问题是,如何将要返回的对象转换为其相应的类型?
下面是我的代码...
public static class ObjectCache
{
private static MemoryCache _cache = new MemoryCache("GetAllMakes");
public static object GetItem(string key)
{
return AddOrGetExisting(key, () => InitialiseItem(key));
}
private static T AddOrGetExisting<T>(string key, Func<T> valueFactory)
{
var newValue = new Lazy<T>(valueFactory);
var oldValue = _cache.AddOrGetExisting(key, newValue, new CacheItemPolicy()) as Lazy<T>;
try
{
return (oldValue ?? newValue).Value;
}
catch
{
_cache.Remove(key);
throw;
}
}
/// <summary>
/// How can i access Value …Run Code Online (Sandbox Code Playgroud) c# ×4
.net ×3
dictionary ×2
asp.net ×1
generics ×1
idictionary ×1
json.net ×1
mapping ×1
memorycache ×1
object ×1