Assign values to the same attribute during object Conversion

Source: Internet
Author: User
Using  System;
Using System. Collections. Generic;
Using System. Web;
Using System. Web. UI;
Using System. Web. UI. webcontrols;
Using System. reflection;

Namespace Weblinq
{
Public Partial Class _ Default: system. Web. UI. Page
{
Protected Void Page_load ( Object Sender, eventargs E)
{

User u = New User ();
U. Age = 18 ;
U. Name = " Rhythmk " ;
Man man = New MAN ();
Setvalue (u, man );
If (Man ! = Null )
{
Response. Write (man. Name );

}
Else {

Response. Write ( " Null " );
}
}

Public Static Void Setvalue ( Object Oldobj, Object Newobj)
{
Type oldtype = Oldobj. GetType ();
Type newtype = Newobj. GetType ();

Propertyinfo [] oldobjpropertyinfos = Oldtype. getproperties ();
For ( Int I = 0 ; I < Oldobjpropertyinfos. length; I ++ )
{
If (Oldobjpropertyinfos [I]. Canread)
{
String Strpropertyname = Oldobjpropertyinfos [I]. Name;
Object Newvalue = Getpropertyvalue (oldobj, strpropertyname );


If (Newvalue ! = Null )
Setpropertyvalue (newobj, strpropertyname, newvalue );
}
}
}

Private Static Void Setpropertyvalue ( Object OBJ, String Strpropertyname, Object Val)
{
Type T = OBJ. GetType ();
Propertyinfo [] propertyinfos = T. getproperties ();
Foreach (Propertyinfo pi In Propertyinfos)
{
If (PI. Name = Strpropertyname)
{
If (PI. canwrite)
Pi. setvalue (OBJ, Val, Null );
}
}
}

Private Static Object Getpropertyvalue ( Object OBJ, String Strpropertyname)
{
Type T = OBJ. GetType ();
Propertyinfo [] propertyinfos = T. getproperties ();
Foreach (Propertyinfo pi In Propertyinfos)
{
If (PI. Name = Strpropertyname)
{
If (PI. Canread)
Return Pi. getvalue (OBJ, Null );
}
}
Return Null ;
}
}
}

It is mainly to avoid assigning values between data classes generated by projects such as LINQ to SQL and actual classes.

Instead of performing

A. property1 = B. property1;

A. property2 = B. property2;

A. property3 = B. property3;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.