繁体   English   中英

使用运行时字符串输入来实例化一个 class

[英]Using runtime string input to instantiate a class

我想使用用户在代码中提供的名称创建 class 的实例。

我知道Activator.CreateInstance方法,它是类似问题的答案,但没有一个例子让我很困惑。

class Program
{
    static void Main()
    {
        Program Pet = new Program();         
        string Name = Pet.GetName();
        Pet.GetSpecies(Name);            
    }

    public void GetSpecies(string name)
    {
        Console.WriteLine($"What species is {name}? We currently see: Dog/Cat/Hamster/Gerbil");
        string answer = Console.ReadLine();
        answer = answer.ToLower();

        if (answer == "dog")
        {
            Console.WriteLine("You have selected: Dog");                
            Dog name = new Dog(); //?
        }                  
    }

    public string GetName()
    {
        Console.WriteLine("And what is your pets name?");            
        string name = Console.ReadLine();
        return name;
    }
}

我将为您提供简单的示例以供您理解。

Type.GetType("Dog")将为名为“Dog”的 class 提供类型 object,然后Activator.CreateInstance(type)将创建此 class 的实例。

Type type = Type.GetType("Dog");
object instance = Activator.CreateInstance(type);

下面为您提供一些评论意见。

您无需创建程序 class 的实例即可调用其方法。 您可以直接调用这些方法。

您正在为 object 使用相同的变量name ,因此请使用相关名称。

也请检查,我认为在异常中调用相同的方法是无关紧要的,请检查。

如果您只想根据用户输入创建 object,也可以使用 go 作为 switch 语句。

switch (answer)
{
    case "dog":
        Console.WriteLine("You have selected: Dog");
        Dog dog = new Dog();
        break;

    case "cat":
        Console.WriteLine("You have selected: Cat");
        Cat cat = new Cat();
        break;

编辑:

您可以像这样调用Bark方法。

MethodInfo method = type.GetMethod("Bark");
method.Invoke(instance, null);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM