[英]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.