我有两个A和B类,我想将A的实例转换为B.最好的方法是什么? 如何创建实用程序类来执行此任务?
public class A
{}
public class B
{}
答案 0 :(得分:3)
一个好的起点是查看Casting and Type Conversions上的MSDN文档。
由于两个类之间没有直接关系,因此您需要编写Conversion Operator。例如:
public class A
{
public int AValue { get; set; }
}
public class B
{
public int BValue { get; set; }
public static explicit operator B(A instanceOfA)
{
return new B { BValue = instanceOfA.AValue };
}
}
然后你可以写:
A instanceOfA = new A { AValue = 7 };
B instanceOfB = (B)instanceOfA;
// Will output "7"
Console.WriteLine(instanceOfB.BValue);
我从此示例中获取的文档位于MSDN上,Using Conversion Operators。
如果两个类之间存在直接关系,例如B
派生自A
,例如:
public class A
{
public int Value { get; set; }
}
public class B : A
{
public string OtherValueSpecificToB { get; set; }
}
如果你想从B转换为A:
,那么你就不需要任何额外的代码B instanceOfB = new B { OtherValueSpecificToB = "b", Value = 3 };
A instanceOfBCastToA = (A)instanceOfB;
// Will output "3";
Console.WriteLine(instanceOfBCastToA.Value);
// Will not compile as when being treated as an "A" there is no "OtherValueSpecificToB" property
Console.WriteLine(instanceOfBCastToA.OtherValueSpecificToB);