C# 字典<;字符串,对象>;反对
转换此词典的最佳方法是:C# 字典<;字符串,对象>;反对,c#,object,dictionary,C#,Object,Dictionary,转换此词典的最佳方法是: Dictionary<string, object> person = new Dictionary<string, object>(); person.Add("ID", 1); person.Add("Name", "Alex"); ? 使用int cast检查时不提供错误 对int cast进行无错误检查。以下是我的建议: va
Dictionary<string, object> person = new Dictionary<string, object>();
person.Add("ID", 1);
person.Add("Name", "Alex");
?
使用int cast检查时不提供错误
对int cast进行无错误检查。以下是我的建议:
var newPerson = new Person
{
ID = (int)person["ID"],
Name = person["Name"].ToString()
};
这没有错误处理,并且假设字段存在于字典中,并用有效值填充 以下是我的建议:
var newPerson = new Person
{
ID = (int)person["ID"],
Name = person["Name"].ToString()
};
这没有错误处理,并且假设字段存在于字典中,并用有效值填充 简单的方法:
var person = new Person
{
Id = (int)dict["ID"],
Name = (string)dict["Name"]
}
通用方法:使用反射。简单方法:
var person = new Person
{
Id = (int)dict["ID"],
Name = (string)dict["Name"]
}
通用方法:使用反射。如果您希望能够对任何对象执行此操作,通常可以使用反射。假设字典中的值是适当的类型且不需要转换:
static T GetObject<T>(Dictionary<string, object> dict)
where T : new()
{
var obj = new T();
foreach (var property in typeof(T).GetProperties())
{
var args = new object[1];
var setter = property.GetSetMethod(); // property has a public setter
if (setter != null && dict.TryGetValue(property.Name, out args[0]))
setter.Invoke(obj, args);
}
return obj;
}
static T GetObject(Dictionary dict)
其中T:new()
{
var obj=新的T();
foreach(typeof(T).GetProperties()中的var属性)
{
var args=新对象[1];
var setter=property.GetSetMethod();//属性有一个公共setter
if(setter!=null&&dict.TryGetValue(property.Name,out args[0]))
setter.Invoke(obj,args);
}
返回obj;
}
然后使用它:
var alexDict = new Dictionary<string, object>
{
{ "ID", 1 },
{ "Name", "Alex" },
};
var alexPerson = GetObject<Person>(alexDict);
var-alexDict=新字典
{
{“ID”,1},
{“Name”,“Alex”},
};
var-alexPerson=GetObject(alexDict);
如果您想在一般情况下对任何对象执行此操作,可以使用反射。假设字典中的值是适当的类型且不需要转换:
static T GetObject<T>(Dictionary<string, object> dict)
where T : new()
{
var obj = new T();
foreach (var property in typeof(T).GetProperties())
{
var args = new object[1];
var setter = property.GetSetMethod(); // property has a public setter
if (setter != null && dict.TryGetValue(property.Name, out args[0]))
setter.Invoke(obj, args);
}
return obj;
}
static T GetObject(Dictionary dict)
其中T:new()
{
var obj=新的T();
foreach(typeof(T).GetProperties()中的var属性)
{
var args=新对象[1];
var setter=property.GetSetMethod();//属性有一个公共setter
if(setter!=null&&dict.TryGetValue(property.Name,out args[0]))
setter.Invoke(obj,args);
}
返回obj;
}
然后使用它:
var alexDict = new Dictionary<string, object>
{
{ "ID", 1 },
{ "Name", "Alex" },
};
var alexPerson = GetObject<Person>(alexDict);
var-alexDict=新字典
{
{“ID”,1},
{“Name”,“Alex”},
};
var-alexPerson=GetObject(alexDict);
查看此链接可能有助于回答您的问题“我希望从Select数据库查询返回对象”。我认为Dictionary类存在误解。您似乎使字典中的两个不同元素对应于一个语义对象。您需要的似乎是一个Dictionary对象,它具有到Person对象的int映射。查看此链接可能有助于回答您的问题“我希望从Select数据库查询返回对象”。我认为Dictionary类存在误解。您似乎使字典中的两个不同元素对应于一个语义对象。您需要的似乎是一个Dictionary对象,它具有到Person对象的int映射。