确定在C#

时间:2018-10-10 08:13:50

标签: c# inheritance console runtime

我想知道使用C#时是否可以在运行时添加子类。

我喜欢在主类上设置一个类型,并且如果可能的话,有一些代码根据此信息选择正确的继承,这是否有可能实现?

这是我喜欢做什么的一个小例子。

关于, 马格努斯

using System;

namespace ClassTest
{

    class Animal
    {
       public string type = "[Not set!]"; // use the correct class based on thi value.

       public virtual string WhatDoesTheAnimalSay()
       {
          return "[no animal selected!]";
       }
    }

   class Cat : Animal
   {
      public override string WhatDoesTheAnimalSay()
      {
         return "Meow!";
      }
   }

   class Dog : Animal
   {
      public override string WhatDoesTheAnimalSay()
      {
         return "Woof!";
      }
   }

   class Program
   {
      static void Main(string[] args)
      {
        // Cat cat = new Cat();
        // Console.WriteLine("The Cat says: " + cat.WhatDoesTheAnimalSay());

        // Dog dog = new Dog();
        // Console.WriteLine("The Dog says: " + dog.WhatDoesTheAnimalSay());

        Animal unknown = new Animal();
        unknown.type = "Dog";
        Console.WriteLine("The " + unknown.type + " says: " + unknown.WhatDoesTheAnimalSay());

        Console.ReadKey();
      }
   }
}

1 个答案:

答案 0 :(得分:2)

替换

Animal unknown = new Animal();
unknown.type = "Dog";

使用

Animal known = new Dog();

并忽略该字符串类型。每个类都有其类型,请参见GetType()