简体   繁体   English

如何将一个属性从一个类复制到另一个类?

[英]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 ; 我要复制从属性personStudent ; 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.

相关问题 如何从一个文件复制数据到另一个文件 - How I can copy data from one file in another one 如何将数据绑定从一个控件复制到另一个控件? - How can I copy the databinding from one control to another? 如何将节点从一个xml文件复制到另一个文件? - How can I copy nodes from one xml file into another? 如何从一个模型类到另一个模型类调用属性值? - How do I call an attribute value from one model class to another model class? 我可以从一个 C# 控制台复制到另一个吗? - Can I copy from one C# console to another? 如何从一个字符串复制到另一个字符串从所需位置到结尾? - How can I copy from one string to another string from the desired location to the end? C#.NET WinForms如何从一个列表复制类的实例 <class> 到另一个列表 <class> 使用剪贴板 - C# .NET WinForms How do I copy instance of class from one List<class> to another List<class> using Clipboard 如何使用AWS api将一个目录的内容复制到另一个目录? - How can I copy contents of one directory to another with the AWS api? 如何将HTML文本框值从一个域复制到另一个域的文本框? - How can I copy HTML textbox values from one domain to another domain's textboxes? 如何将所有TableAdapter从一个DataSet复制到另一个DataSet? - How can I copy all TableAdapters from one DataSet to another DataSet?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM