Upcasting如何保留派生类的属性? [英] How Upcasting preserve derived classes's Properties?

查看:72
本文介绍了Upcasting如何保留派生类的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

        static void Main(string[] args)
        {
            Student student = new Student()
            {
                ID = 12,
                Name = "Manu",
                LastName = "Shekar"
            };

            Iregister x = student;
            Student newstudent = x as Student;

           //Console.WriteLine(x.LastName); //Uncommenting this shows compilation error
            Console.WriteLine(newstudent.LastName); //This Show "Shekar"
            Console.ReadKey();

        }


    class Student : Iregister
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public String LastName { get; set; }

    }
    interface Iregister
    {
        int ID { get; set; }
        String Name { get; set; }


    }

我想知道 newstudent.LastName 获得正确的值,因为它是从没有 LastName Iregister 强制转换而来的code>属性?
如何将值 Shekar从 student.LastName 传递到 newstudent.LastName x 是否将其存储在两者之间?如果我想念一些基础知识,请原谅我。

I wonder how the newstudent.LastName gets the correct value since it is casted from Iregister which doesn't have LastName property? How the value "Shekar" is passed from student.LastName to newstudent.LastName. Did x stores it somewhere in between? Pardon me if i miss something basics.

推荐答案

您创建一个对象,并在变量<$ c中为其指定一个引用$ c>学生

You create a single object, and assign a reference to it in the variable student.

然后为同一对象创建第二个 reference 并将其分配给 x x student 都指向同一个对象,但是 x 变量意味着仅在 IRegister 上定义的成员可用。

You then create a second reference to the same object and assign that to x. Both x and student are referring to the same object, but the type of the x variable means that only the members defined on IRegister are available.

然后创建一个第三次引用同一对象,并将其分配给 newstudent 。由于 newstudent 的类型为 Student ,因此您可以访问 Student的所有成员

You then create a third reference to the same object and assign that to newstudent. Since newstudent is of type Student, you can access all of the member of Student from that reference.

不是变量只存储引用。是 object 存储自己的实际数据,并且该对象在整个过程中保持不变。

Not that the variables just store references. It's the object that stores its own actual data, and that object remained unchanged throughout the process.

这篇关于Upcasting如何保留派生类的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆