0
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();

我想将属性从复制personStudent;怎么可能?

4

4 回答 4

4

您可以使用继承来简化此操作。

class Student : Person
{

}
于 2012-05-14T12:15:16.580 回答
0

我假设“属性”实际上是指“财产”......

没有“自动”的方法可以做到这一点,您需要手动复制这些值。

Person p = ...
Student s = new Student { FirstName  = p.FirstName, LastName = p.LastName };

根据上下文,您还可以使用像AutoMapper这样的对象映射器

于 2012-05-14T12:14:40.337 回答
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
{
}
于 2012-05-14T12:15:19.730 回答
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);
}
于 2012-05-14T12:18:19.350 回答