简体   繁体   中英

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

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 .

If there was a direct relationship between the two classes, for example B derives from A , for example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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