如何在 C# 中扩展类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15251167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:41:07  来源:igfitidea点击:

How to extend a Class in C#?

c#.net

提问by markzzz

I have my own Object, and I'd like to extend it, saving data from a person and adding new info.

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

So the code would be:

所以代码将是:

public class Student : Person
{
    public string code { get; set; }
}

but when I try to init it and add the new value:

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

Person person = new Person("Paul", "Catch");
Student student = (Person)person;
student.code = "1234";

I got System.InvalidCastException: Unable to cast object of type 'MyLayer.Person' to type 'Student'.

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

Am I missing some point?

我错过了什么吗?

EDIT: maybe I wrong putting that Person class. You must suppose it become from a DB as object, such as Person person = new MyPersons().First();

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

So I won't to populate the new one with properties one by one, just extend one property thanks to the new object that extend the old one.

因此,我不会用属性一一填充新属性,而是通过扩展旧属性的新对象扩展一个属性。

采纳答案by Parimal Raj

You cannot convert a Personto Studentdirectly.

您不能直接将 a 转换PersonStudent

Inheritance in OOP comes with hierarchy level, i.e. you can cast the derivedclass to baseclass, but the opposite is not possible. You cannot cast base class to derived class

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

One possible solution is :

一种可能的解决方案是:

Create Studentfrom Person using constructor overload.

创建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
    }
}

回答by poitroae

Assign a Studentto your Person.

将 a 分配Student给您的Person.

Person person = new Student("Paul", "Catch");
Student student = (Person)person;
student.code = "1234";

Note that this makes all the casting pretty useless, better is:

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

Student student = new Student("Paul", "Catch");
student.code = "1234";

回答by Riddick

Your conversion is incorrect, a person can become a student (Not the other way round)

您的转换不正确,一个人可以成为学生(而不是相反)

Change to:

改成:

Student student = (Student)person;

Although your type cast can be avoided ..

虽然可以避免您的类型转换..

Person person = new Person("Paul", "Catch");
Student student = (Person)person;
student.code = "1234";

Becomes ....

变成....

Student student = new Student("Paul", "Catch");
student.code = "1234";

回答by Jason

In your Studentclass, add this constructor, assuming you have a constructor that takes two strings in the Personclass

在你的Student类中,添加这个构造函数,假设你有一个在Person类中接受两个字符串的构造函数

public Student(string val1, string val2) : base(val1, val2) { }

then you can use it like this

那么你可以像这样使用它

Student student = new Student("Paul", "Catch");
student.code = "1234";

回答by raynjamin

The problem you're seeing is that in your assignment, you're trying to downcast Person to Student. This isn't possible, because the object is a Person, and the Person type has no knowledge of Student.

您看到的问题是,在您的作业中,您试图将 Person 贬低为 Student。这是不可能的,因为对象是一个 Person,而 Person 类型不知道 Student。

My interpretation of it is that objects have a specific type, regardless of how you cast it. A cast (like the way light is cast on an object) just dictates how you see that object. In the example case, a Person has no knowledge of a Student, therefore no matter how you look at it, you can't assign it to student.

我对它的解释是对象有一个特定的类型,不管你如何转换它。投射(就像光线投射在物体上的方式)只是决定了您如何看待该物体。在示例中,Person 不了解 Student,因此无论您如何看待它,都无法将其分配给 student。

A Student object, however, can be upcast to a Person, since every Student is a Person. You can always upcast to base classes, but you can't always downcast to derived classes.

然而,Student 对象可以向上转换为 Person,因为每个 Student 都是一个 Person。您总是可以向上转换为基类,但不能总是向下转换为派生类。

I hope this gives you some clarity. (I also hope I got this totally right.)

我希望这能让你清楚一些。(我也希望我完全正确。)