如何在C#中扩展一个类?

mar*_*zzz 13 .net c#

我有自己的对象,我想扩展它,从一个人保存数据并添加新信息.

所以代码是:

public class Student : Person
{
    public string code { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试初始化并添加新值时:

Person person = new Person("Paul", "Catch");
Student student = (Person)person;
student.code = "1234";
Run Code Online (Sandbox Code Playgroud)

我有 System.InvalidCastException: Unable to cast object of type 'MyLayer.Person' to type 'Student'.

我错过了一些观点吗?

编辑:也许我错了把那个Person类.您必须假设它从数据库变为对象,例如Person person = new MyPersons().First();

所以我不会逐个填充新属性,只需扩展一个属性,这要归功于扩展旧属性的新对象.

PaR*_*RaJ 23

您无法直接将a转换PersonStudent.

OOP中的继承随附hierarchy level,即你可以将derived类强制转换为base类,但是opposite is not possible.You cannot cast base class to derived class

一种可能的解决方案是

Student使用人员创建constructor overload.

public class Person
{
    public string FName { get; set; }
    public string LName { get; set; }

    public Person(string fname, string lname)
    {
        FName = fname;
        LName = lname;
    }
}

public class Student : Person
{
    public Student(Person person, string code)
        : base(person.FName, person.LName)
    {
        this.code = code;
    }
    public Student(Person person)
        : base(person.FName, person.LName)
    {

    }

    public string code { get; set; }
}



static class Program
{
    static void Main(string[] args)
    {
        Person person = new Person("Paul", "Catch");

        // create new student from person using 
        Student student = new Student(person, "1234"); 
        //or
        Student student1 = new Student(person);
        student1.code = "5678";

        Console.WriteLine(student.code); // = 1234
        Console.WriteLine(student1.code); // = 5678
    }
}
Run Code Online (Sandbox Code Playgroud)


poi*_*oae 5

将 a 分配Student给您的Person.

Person person = new Student("Paul", "Catch");
Student student = (Person)person;
student.code = "1234";
Run Code Online (Sandbox Code Playgroud)

请注意,这使得所有铸造都毫无用处,更好的是:

Student student = new Student("Paul", "Catch");
student.code = "1234";
Run Code Online (Sandbox Code Playgroud)