如何使用新的类别值填充当前类别?
这个有点难以解释,所以我将首先显示代码..
注意:使示例不那么混乱
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); } }
This one is a little difficult to explain so I'll show code first..
Note: Made example less confusing
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 } }
Thanks for help.. here what I did.. Created this in my extension class.. so I can now do
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); } }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能。
您可以手动复制属性,或将构造函数替换为返回
row.ToClass1()
的静态工厂方法。You can't.
You can either manually copy over the properties, or replace the constructor with a static factory method that returns
row.ToClass1()
.手动设置每个值可能会更容易。
也就是说,如果类中每个属性的 DataRow 列名都相同,并且如果类型也相同,则可以使用 Reflection 来设置属性名称。你会这样做:
It'll probably be easier to manually set each value.
That said, if the column name of the DataRow is the same for each property in your class, and if the types are equally the same, you could use Reflection to set the property name. You would do it somewhat like this: