// 定义两个具有完全相同成员的类
class A
{
public String S = "A";
public int Val = 1;
private double DVal = 10.1;
}
class B
{
public String S = "B";
public int Val = 2;
private double DVal = 20.1;
}
static class Program
{
[STAThread]
static void Main( params string[] args )
{
A a = new A();
B b = CopySameFieldsObject< B >( a ); // 把A的对象转换到B对象
B b2 = new B();
A a2 = CopySameFieldsObject< A >( b2 ); // 反过来测试下
}
// 假定输入类于与返回类具有完全相同的字段
static T CopySameFieldsObject< T >( Object source )
{
Type _SrcT = source.GetType();
Type _DestT = typeof( T );
// 构造一个要转换对象实例
Object _Instance = _DestT.InvokeMember( "", BindingFlags.CreateInstance, null, null, null );
// 这里指定搜索所有公开和非公开的字段
FieldInfo[] _SrcFields = _SrcT.GetFields( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance );
// 将源头对象的每个字段的值分别赋值到转换对象里,因为假定字段都一样,这里就不做容错处理了
foreach( FieldInfo field in _SrcFields )
{
_DestT.GetField( field.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).
SetValue( _Instance, field.GetValue( source ) );
}
return ( T )_Instance;
}
}
自定义类型转换(具有完全相同成员)
最新推荐文章于 2022-05-31 15:26:08 发布