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

  • Thread starter Thread starter zlf
  • Start date Start date
Z

zlf

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
 
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.

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

Jon
 
zlf said:
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.

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);
}
}
 
Back
Top