C#继承:如何将父对象分配给子实例
在C#中,我有一个父类和子类,如下所述:C#继承:如何将父对象分配给子实例,c#,inheritance,C#,Inheritance,在C#中,我有一个父类和子类,如下所述: public class Parent { public int Id { get; set; } public string Name { get; set;} public int Age { get; set; } } public class Child: Parent { public string ChildName { get; set; } } 现在我有一个父类的对象: var parent =
public class Parent
{
public int Id { get; set; }
public string Name { get; set;}
public int Age { get; set; }
}
public class Child: Parent
{
public string ChildName { get; set; }
}
现在我有一个父类的对象:
var parent = new Parent() { Id: 1, Name: "Parent-A", Age: 56 };
如何将此父对象指定给子对象的实例
var child = new Child();
child = parent; // How to assign object of parent to the child instance here
child.ChildName = 'Child-A';
不能将父类对象指定给子类变量,这将违反继承原则,但如果要从父类创建新的子类对象
using System;
class HelloWorld {
static void Main() {
var parent = new Parent() { Id = 1, Name = "Parent-A", Age = 56 };
var child = new Child(parent); // How to assign object of parent to the child instance here
child.ChildName = "Child-A";
}
}
public class Parent
{
public int Id { get; set; }
public string Name { get; set;}
public int Age { get; set; }
}
public class Child: Parent
{
public Child():base(){
}
public Child(Parent parent):base(){
this.Id =parent.Id;
this.Name =parent.Name;
this.Age =parent.Age;
}
public string ChildName { get; set; }
}
显式指定类型。那就是。。。不要使用
var
。你不能。父母不是孩子的类型,就像动物不是狗的类型一样。parent
比child
小,因此将parent
类型的实例分配给child
类型的变量是无效的,因为没有足够的变量。(这是一个比喻,不要从字面上理解。)除了指定ChildName
@confusedDeveloper外,您需要做的是将parent
的属性复制到child
中。我想澄清一下您想要的结果会是什么样子会更好。