使用来自子 class 的 class 的实例初始化父 class 的成员

Initialize the members of parent class with an instance of that class from the child class

我有以下 class:

public class A
{
    public object Property1 { get; set; }
    public object Property2 { get; set; }
    public object Property3 { get; set; }

    //And for the sake of the example another 20 fields/properties

    public A()
    {

    }
}

还有一个class:

public class B : A
{
     //Bunch of other properties...
}

我有一个方法(来自我无法更改的不同程序集)returns A 的新实例 class。

有没有办法 cast/convert/initialize class B 具有 class A 的所有属性和字段(以及私有字段)?

我无法更改 class A 中的任何内容(它来自不同的程序集)

是否可以在不更改继承的情况下实现这一点?

一个人认为要考虑的是组合优于继承

class B
{
    public A InstanceOfA { get; set; }
}

然后你可以很容易地创建一个B的实例并给它一个A的实例。

你问的可以实现。您可以轻松地复制所有属性的值,这是肯定的,但是对于字段,您必须使用反射来获取它们的值,因为如果 A 是按 A 类型创建的,则不能简单地将 A 转换为 B。

Is there a way to cast/convert/initialize class B

您可以像下面的例子那样尝试显式类型转换

struct Digit
{
byte value;

public Digit(byte value)  //constructor
{
    if (value > 9)
    {
        throw new System.ArgumentException();
    }
    this.value = value;
}

public static explicit operator Digit(byte b)  // explicit byte to digit conversion operator
{
    Digit d = new Digit(b);  // explicit conversion

    System.Console.WriteLine("Conversion occurred.");
    return d;
}
}

class TestExplicitConversion
{
    static void Main()
    {
        try
        {
            byte b = 3;
            Digit d = (Digit)b;  // explicit conversion
        }
        catch (System.Exception e)
        {
            System.Console.WriteLine("{0} Exception caught.", e);
        }
    }
}

从 msdn 复制代码 => Using Conversion Operators