是否有任何优雅的快速方法将对象映射到字典,反之亦然?
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) 我正在尝试将字典转换为匿名类型,每个键都有一个属性.
我尝试谷歌它,但我能找到的是如何将匿名对象转换为字典.
我的字典看起来像这样:
var dict = new Dictionary<string, string>
{
{"Id", "1"},
{"Title", "My title"},
{"Description", "Blah blah blah"},
};
Run Code Online (Sandbox Code Playgroud)
我想返回一个看起来像这样的匿名对象.
var o = new
{
Id = "1",
Title = "My title",
Description = "Blah blah blah"
};
Run Code Online (Sandbox Code Playgroud)
所以我希望它循环遍历字典中的每个keyValuePair并在对象中为每个键创建一个属性.
我不知道从哪里开始.
请帮忙.
我一直在研究C#中的反射,并且想知道我是否使用带有键的字典 - 值可以创建一个带有变量的对象,其中包含字典中每个键的名称及其值,该词典的关键价值.
我有一个相反的方法,它从字典中提取一个对象,这个字典包含键和类属性及其值,属性的值.
我想知道如果可能的话怎么做.
下面是我的方法,它提取对象的字典:
protected Dictionary<String, String> getObjectProperty(object objeto)
{
Dictionary<String, String> dictionary = new Dictionary<String, String>();
Type type = objeto.GetType();
FieldInfo[] field = type.GetFields();
PropertyInfo[] myPropertyInfo = type.GetProperties();
String value = null;
foreach (var propertyInfo in myPropertyInfo)
{
if (propertyInfo.GetIndexParameters().Length == 0)
{
value = (string)propertyInfo.GetValue(objeto, null);
value = value == null ? null : value;
dictionary.Add(propertyInfo.Name.ToString(), value);
}
}
return dictionary;
}
Run Code Online (Sandbox Code Playgroud) 从Gremlin.Net响应中获取POCO的最佳方法是什么?
现在,我手动转换为字典:
var results = await gremlinClient.SubmitAsync<Dictionary<string, object>>("g.V()");
var result = results[0];
var properties = (Dictionary<string, object>)result["properties"];
var value = ((Dictionary<string, object>)properties["myValue"].Single())["value"];
Run Code Online (Sandbox Code Playgroud) 我试图将一个FormCollection传递给我的ASP.NET MVC控制器并将其转换为动态对象,然后将其序列化为Json并传递给我的Web API.
[HttpPost]
public ActionResult Create(FormCollection form)
{
var api = new MyApiClient(new MyApiClientSettings());
dynamic data = new ExpandoObject();
this.CopyProperties(form, data); // I would like to replace this with just converting the NameValueCollection to a dynamic
var result = api.Post("customer", data);
if (result.Success)
return RedirectToAction("Index", "Customer", new { id = result.Response.CustomerId });
ViewBag.Result = result;
return View();
}
private void CopyProperties(NameValueCollection source, dynamic destination)
{
destination.Name = source["Name"];
destination.ReferenceCode = source["ReferenceCode"];
}
Run Code Online (Sandbox Code Playgroud)
我见过将动态对象转换为Dictionary或NameValueValueCollection的示例,但需要采用其他方式.
任何帮助,将不胜感激.
c# ×4
dictionary ×2
.net ×1
asp.net-mvc ×1
gremlin ×1
idictionary ×1
mapping ×1
object ×1
reflection ×1