是否有任何优雅的快速方法将对象映射到字典,反之亦然?
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中,我希望我的类属性为KEY,特殊属性的值为VALUE
假设我的班级是
public class Location
{
public string city { get; set; }
public string state { get; set; }
public string country { get; set;
}
Run Code Online (Sandbox Code Playgroud)
现在假设我的数据是
city = Delhi
state = Delhi
country = India
Run Code Online (Sandbox Code Playgroud)
现在你可以轻松理解我的观点!
我想制作字典!那本字典应该是这样的
Dictionary<string,string> dix = new Dictionary<string,string> ();
dix.add("property_name", "property_value");
Run Code Online (Sandbox Code Playgroud)
我可以获得价值!但是我怎样才能得到属性名称(而不是价值)?
我应该编码什么来创建它动态!这应该适用于我想要的每一堂课?
你可以理解这个问题
我怎样才能从特定类中获取属性列表?
我今天遇到了以下问题,我想知道我的问题是否有解决方案.
我的想法是构建匿名类并将其用作WinForm BindingSource的数据源:
public void Init()
{
var option1 = new
{
Id = TemplateAction.Update,
Option = "Update the Templates",
Description = "Bla bla 1."
};
var option2 = new
{
Id = TemplateAction.Download,
Option = "Download the Templates",
Description = "Bla bla 2."
};
var list = new[] {option1, option2}.ToList();
bsOptions.DataSource = list; // my BindingSource
// cboTemplates is a ComboBox
cboTemplates.DataSource = bsOptions;
cboTemplates.ValueMember = "Id";
cboTemplates.DisplayMember = "Option";
lblInfoTemplates.DataBindings.Add("Text", bsOptions, "Description");
}
Run Code Online (Sandbox Code Playgroud)
到目前为止工作正常.
我遇到的问题是从BindingSource的"Current"属性中获取Id,因为我无法将其强制转换为匿名类型:
private void cmdOK_Click(object …Run Code Online (Sandbox Code Playgroud)