[英]How can I copy one attribute from one class to another?
class person
{
[Required(ErrorMessage = "Please enter the FirstName of person")]
string FirstName{get; set ;}
[Required(ErrorMessage = "Please enter the LastName of person")]
string LastName{get; set ;}
}
class Student
{
string FirstName{get; set ;}
string LastName{get; set ;}
}
Person p = new Person();
Student s = new Student();
I want to copy the attributes from person
to Student
; 我要复制从属性
person
给Student
; How can it? 怎么会
You could use inheritance to make this easier. 您可以使用继承来简化此过程。
class Student : Person
{
}
I assume that by "attribute", you actually mean "property"... 我认为,“属性”实际上是指“财产” ...
There's no "automatic" way to do it, you need to copy the values manually. 没有“自动”方法,您需要手动复制值。
Person p = ...
Student s = new Student { FirstName = p.FirstName, LastName = p.LastName };
Depending on the context, you could also use an object mapper like AutoMapper 根据上下文的不同,您还可以使用对象映射器(例如AutoMapper)
If Student
inherits Person
, it will both have the properties, and both their attributes. 如果
Student
继承Person
,则将同时具有属性和属性。
class Person
{
[Required(ErrorMessage = "Please enter the FirstName of person")]
string FirstName { get; set; }
[Required(ErrorMessage = "Please enter the LastName of person")]
string LastName { get; set; }
}
class Student : Person
{
}
You could use reflection like this : 您可以像这样使用反射:
foreach (var getter in s.GetType().GetProperties())
{
var newData = getter.GetValue(newProject, null);
var setter = p.GetType().GetProperty(prop.Name)
setter.SetValue(p, newData, null);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.