如何在c#中将一个类对象分配给另一个类对象

时间:2015-10-12 19:51:23

标签: c#

我有2个类,除了名字之外完全相同。我没有 访问任何一个类以更改其中的任何内容。 在我的代码中,我需要将一个类中的一个复制到另一个类。我怎么能够 做这个?

class A
{
     string a;
}

class b
{
     string a;
}

     a a1=new a();
     b b1=new b1();
     a1=b1;

我想在c#代码中将一个类对象分配给另一个类对象。

3 个答案:

答案 0 :(得分:4)

您无法在显示的代码中将A的实例分配给b类型的变量(或反向)。类具有相同字段的事实并不意味着可以将一个字段隐式转换为另一个字段。您无法更改任何类型的最佳方法是创建一种方法,该方法采用一种类型并创建另一种类型的新实例,复制相关值。

答案 1 :(得分:2)

将ObjectA序列化为json字符串,然后将其序列化为ObjectB。

答案 2 :(得分:0)

听起来你可能会问关于施法?像其他提到的那样,这不会对类本身起作用。您可以遍历要转换的类中的每个对象/字符串,并以这种方式转换每个对象。这似乎是你想要最终实现的目标。

 // Create a new derived type.
 Giraffe g = new Giraffe();

 // Implicit conversion to base type is safe.
 Animal a = g;

 // Explicit conversion is required to cast back
 // to derived type. Note: This will compile but will
 // throw an exception at run time if the right-side
 // object is not in fact a Giraffe.
 Giraffe g2 = (Giraffe) a;

来源:https://msdn.microsoft.com/en-us/library/ms173105.aspx

相关问题