Copy all data from a:Class A's fields to the namesake fields of b:Class B.

Copy all data from a:Class A's fields to the namesake fields of b:Class B.

Post by zlf » Thu, 12 Jul 2007 00:28:09


I have two class with nearly exactly same attributes, the only difference is
class B's property setter does some argument checking.

[Serializable]
class A
{
private string a;

public string AA
{
get { return a; }
set { a = value; }
}
}

[Serializable]
class B
{
private string a;

public string AA
{
get { return a; }
set
{
if (string.IsNullOrEmpty(value))
{
throw new ApplicationException();
}
a = value;
}
}
}

I want to do the following:
A a = new A();
a.AA = "123123";
B b = (B)a; -- Copy a's attribute values to b.
Please tell me how to implement a generic function to support copying
namesake fields from one class instance to another even when they belongs to
different class type.

Thanks.

zlf
 
 
 

Copy all data from a:Class A's fields to the namesake fields of b:Class B.

Post by Jon Skeet » Thu, 12 Jul 2007 00:38:25


<snip>


Basically you want generics - look into Type.GetProperties and
Type.GetFields.

Jon

 
 
 

Copy all data from a:Class A's fields to the namesake fields of b:Class B.

Post by Alberto Po » Thu, 12 Jul 2007 00:58:35


Basically you want something along these lines:

using System.Reflection;
...
private void Copy(object src, object dst);
{
Type tDst = dst.GetType();
foreach (PropertyInfo propSrc in src.GetType().GetProperties())
{
propDest=tDst.Properties(pi.Name);
if (propDest!=null) propDest.SetValue(dst, propSrc.GetValue(src,
null), null);
}
}