简体   繁体   English

将一个类对象转换为其他类对象

[英]Cast one class object to other class object

I have two classes A and B and I want to cast an instance of A to B. What's the best way? 我有两个A和B类,我想将A的实例转换为B.最好的方法是什么? How Can I make a utility class to perform this task? 如何创建实用程序类来执行此任务?

public class A
{}
public class B
{}

A good place to start is by reviewing the MSDN documentation on Casting and Type Conversions . 一个好的起点是查看关于Casting和Type Conversions的MSDN文档。

As there's no direct relationship between the two classes, you'll need to write a Conversion Operator . 由于两个类之间没有直接关系,因此您需要编写转换运算符 For example: 例如:

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 };
    }
}

You could then write: 然后你可以写:

A instanceOfA = new A { AValue = 7 };
B instanceOfB = (B)instanceOfA;

// Will output "7"
Console.WriteLine(instanceOfB.BValue);

The documentation I've derived this example from is on MSDN, Using Conversion Operators . 我从这个例子中得到的文档是在MSDN上, 使用转换运算符

If there was a direct relationship between the two classes, for example B derives from A , for example: 如果两个类之间存在直接关系,例如B派生自A ,例如:

public class A
{
    public int Value { get; set; }
}

public class B : A
{
    public string OtherValueSpecificToB { get; set; }
}

You wouldn't then need any extra code if you wanted to cast from B to A: 如果你想从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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM