[C#]关于多态性的问题 [英] [C#] question about the polymorphism

查看:146
本文介绍了[C#]关于多态性的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨.我对此感到困惑:

Hi. Im getting confused with this:

using System;

namespace CSharp_Practicing
{
    class Program
    {
        static void Main()
        {
            Person p = new Student(); // Here in this line im getting confused. I am making a reference of type Person and making this reference point to the Student constructor right ? 
            p = p as Student; // In this line im doing a cast to Student but still cant access the ID property
            
        }
    }

    class Person
    {
        public int Age { get; set; }
        public string Name { get; set; }
    }

    class Student : Person
    {
        public int ID { get; set; }
    }
}



我尝试过的事情:



What I have tried:

Searching for information in the internet but can''t find explaination for this.

推荐答案

Person p = new Student();

似乎是类型不匹配:Person对象不能容纳Student对象.

它无法容纳p.ID作为成员,因为它没有位置.

考虑是否有一个类型为Point()的对象,该对象是作为成员的整数对(x,y).

Appears to be a type mismatch: a Person object cannot hold a Student object.

It cannot hold p.ID as a member as there''s no place for it.

Consider if you have an object of type Point(), which is an integer pair (x, y) as members.

int q = new Point();  // makes no sense.  Does q hold x or y


我认为当您这样做时:
I think when you do:
Person p = new Student();

您松开了ID,因为p现在是Person类,因此您应该用途:

you loose the ID, as p is now a Person class, so you should use:

Student p = new Student();


您正在尝试分配p,类型为Person,作为学生,即使它的类型仍然是不包含ID属性的Person.

您需要将您的演员表声明为Student并声明一个新变量,例如"student".

例如:

You are trying to assign p, of type Person, as student even though its type is still Person which contains no Id property.

You need to declare your cast as Student to a new variable, say "student".

Ex:

Person p = new Student();
        
        // still of type Person so cannot access Id since there is no Id on class Person
        p = p as Student;

        Student student = p as Student;
        var studentId = student.Id;


这篇关于[C#]关于多态性的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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