简体   繁体   English

如何从字符串创建类并调用它的方法?

[英]How to create class from string and call method of it?

I am trying to receive a string input and integer input from a user and then use those inputs to call a method with a specific parameter. 我正在尝试从用户那里接收字符串输入和整数输入,然后使用这些输入来调用具有特定参数的方法。 For example: 例如:

string object_name   = Dog;
int method_parameter = 5;

object_name.Bark(method_parameter);

Here is the actual code: 这是实际的代码:

Console.WriteLine("Please Enter Your First Name. ");
string namez = Console.ReadLine();

Console.WriteLine("Enter 1 to sign in or 2 to sign out. ");
int ez = Console.ReadLine();

Console.WriteLine("Please Enter Your Pin.");
int inpu_pin = int.Parse(Console.ReadLine());

if (ez == 1)
    namez.OnSignIn(inpu_pin);
if (ez == 2)
    namez.OnSignOut(inpu_pin);

Better way is to make use of Factory method pattern can return you object. 更好的方法是利用Factory方法模式可以返回您的对象。

public class Factory
{
  public static object GetAnimal(string objectName)
  {
    if(objectName == "Dob")
     return new Dog();
    else(objectName == "xyz")
     return new xyz(); 
  } 
}

or you can create parent interface for all animal type and return value of factory should be that interface type instead of object. 或者您可以为所有动物类型创建父接口,并且工厂的返回值应为该接口类型而不是对象。

and then do like this 然后像这样

  // reflection
  Object obj = Factory.GetAnimal(args[0]).GetType(); //args[0]="Dog"
  obj.GetMethod("Bark").Invoke(obj,  new object[]{ int.Parse(args[1] });

you have to make use of reflection and have to do like this 您必须利用反射,并且必须这样做

System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(string className)

or if you know fully qualified name do like this 或者如果您知道完全合格的姓名,请这样做

string typeName = args[0]; //"Dog";
string formTypeFullName = string.Format("{0}.{1}", this.GetType().Namespace, typeName);
Type type = Type.GetType(formTypeFullName, true);
Dog dog = (Dog)Activator.CreateInstance(type);
dog.Bark(int.Parse(args[1]));

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

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