如何用新的类值填充当前类?
这个有点难以解释,所以我会先显示代码。
注意:让示例更少混淆
public class Class1
{
public string Title {get;set;}
public string Name {get;set;}
public Class1(Class1 class1)
{
// ?? How do I populate current class with new class values?
// ?? this = class1; - Does not work
// I want to avoid having to manually set each value
}
}
感谢您的帮助..在这里我做了什么..在我的扩展类创建这个..所以我现在可以做
Extensions.MapValues(class1, this);
public static void MapValues(object from, object to)
{
var fromProperties = from.GetType().GetProperties();
var toProperties = to.GetType().GetProperties();
foreach (var property in toProperties) {
var fromProp = fromProperties.SingleOrDefault(x => x.Name.ToLower() == property.Name.ToLower());
if(fromProp == null) {
continue;
}
var fromValue = fromProp.GetValue(from, null);
if(fromValue == null) {
continue;
}
property.SetValue(to, fromValue, null);
}
}
手动设置每个值可能更容易。
也就是说,如果DataRow的列名与您的类中的每个属性相同,并且类型相同,则可以使用Reflection来设置属性名称。 你会这样做:
public Class1(DataRow row)
{
var type = typeof(Class1);
foreach(var col in row.Table.Columns)
{
var property = type.GetProperty(col.ColumnName);
property.SetValue(this, row.Item(col), null);
}
}
你不能。
您可以手动复制属性,也可以使用返回row.ToClass1()的静态工厂方法替换构造函数。
上一篇: How do I populate current class with new class values?
下一篇: Adding sites to Trusted list in IE (all versions above 6)
