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();
我想将属性从person
复制到Student
;
它怎么样?
答案 0 :(得分:4)
您可以使用继承来简化这一过程。
class Student : Person
{
}
答案 1 :(得分:0)
我认为通过“属性”,你实际上是指“财产”......
没有“自动”方式,您需要手动复制值。
Person p = ...
Student s = new Student { FirstName = p.FirstName, LastName = p.LastName };
根据上下文,您还可以使用AutoMapper
之类的对象映射器答案 2 :(得分:0)
如果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
{
}
答案 3 :(得分:0)
您可以使用这样的反射:
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);
}