本文介绍了什么是虚拟类的真实例子,为什么我们使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经历了抽象,虚拟和界面。但我仍然无法理解为什么这些在编程中使用。请用一些实际的例子向我解释这个概念。

I have gone through the abstract, virtual and interfaces. But I still can't understand why does these use in the programming. Please, explain me this concept with some real life examples.

推荐答案


using System;

namespace SayHello
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            EnglishPerson e = new EnglishPerson();
            GermanPerson g = new GermanPerson();

            Console.WriteLine(e.SayHello + " " + e.SayName());
            Console.WriteLine(g.SayHello + " " + g.SayName());

            Console.ReadKey();
        }
    }

    public interface IPerson
    {
        int Age { get; }

        string SayHello { get; }

        string SayName();
    }

    public abstract class Person : IPerson
    {
        private DateTime dob = DateTime.Now.AddYears(-50);

        //Implemented in base class
        public int Age
        {
            get
            {
                return DateTime.Today.Year - dob.Year;
            }
        }

        public virtual string SayHello
        {
            get
            {
                return "Hello";
            }
        }

        public abstract string SayName();
    }

    public class GermanPerson : Person
    {
        public override string SayHello
        {
            get
            {
                return "Guten Tag";
            }
        }

        public override string SayName()
        {
            return ("Ich heiße Johan");
        }
    }

    public class EnglishPerson : Person
    {
        public override string SayName()
        {
            return "My name is Jon";
        }
    }
}



这篇关于什么是虚拟类的真实例子,为什么我们使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 04:40