Never give up

C#中Override的一个用法

上一篇 / 下一篇  2016-12-05 12:12:01

定义一个Student的Class类
在输出时,直接回去调用ToString()这个Method
using System;
namespace tutorialspoint
{
    class Student
    {
        private string code = "N.A";
        private string name = "not known";
        private int age = 0;

        // Declare a Code property of type string:
        public string Code
        {
            get
            {
                return code;
            }
            set
            {
                code = value;
            }
        }

        // Declare a Name property of type string:
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }

        // Declare a Age property of type int:
        public int Age
        {
            get
            {
                return age;
            }
            set
            {
                age = value;
            }
        }
        public override string ToString()
        {
            return "Code = " + Code + ", Name = " + Name + ", Age = " + Age;
        }
    }

    class ExampleDemo
    {
        public static void Main()
        {

            // Create a new Student object:
            Student s = new Student();

            // Setting code, name and the age of the student
            s.Code = "001";
            s.Name = "Zara";
            s.Age = 9;
            Console.WriteLine("Student Info: {0}", s.ToString());

            //let us increase age
            s.Age += 1;
            Console.WriteLine("Student Info: {0}", s);
            Console.ReadKey();
        }
    }
}

TAG:

 

评分:0

我来说两句

我的栏目

日历

« 2024-04-16  
 123456
78910111213
14151617181920
21222324252627
282930    

数据统计

  • 访问量: 21449
  • 日志数: 14
  • 建立时间: 2016-10-17
  • 更新时间: 2017-06-28

RSS订阅

Open Toolbar