简体   繁体   English

如果我只有类的字符串名称,该如何在静态类上调用方法?

[英]How do I call a method on a static class if I've only got the classes string name?

For example I have a list of strings that happen to be the names of static classes and depending on which string name is selected I just want to use that static class. 例如,我有一个字符串列表,这些字符串恰好是静态类的名称,并且根据选择的字符串名称,我只想使用该静态类。 I know what the method is called on the static class, and it is the same on each class. 我知道在静态类上调用的方法,并且每个类上都相同。

If the strings were "x", "y", "z" and the selected string is "z" and the method is called process() , then in my code it would call x.process() in some way, x being the name of an actual static class. 如果字符串是“ x”,“ y”,“ z”且所选字符串是“ z”且该方法称为process() ,那么在我的代码中它将以某种方式调用x.process() ,x为实际静态类的名称。

Remember these are static classes. 记住这些是static类。

You would use reflection but include the namespace with the class name. 您将使用反射,但在namespace包含class名称。

Type type = Type.GetType("namespace.x");
MethodInfo process = type.GetMethod("process");
process.Invoke(null, null);

暂无
暂无

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

相关问题 如何从另一个类的静态方法(即只有一个对象)调用实例方法? - How do I call an instance method from another classes' static method (i.e. have only one object)? 我已经开始了一个过程,如何在该过程中调用方法 - I've started a process, how do I call a method in that process 如何在类中为泛型类型调用静态方法? - How do I call static method for a generic type in a class? C#:如何从派生类的静态方法调用基类的静态方法? - C#: How do I call a static method of a base class from a static method of a derived class? 如何确保类可以在另一个类上调用方法,但其他类不能调用该方法? - How do I ensure a Class can call a method on another Class, but not other Classes can call that method? 如何从其他类的静态方法中调用非静态方法? - How do I call a non-static method from a static method from a different class? 如何在运行时转换为从String(=类的名称)获得的类型? - How do I cast into a type that I got from a String(=the name of the class) at runtime? 在非静态类中,如何保留同时在多个不同类中调用的静态方法中使用的静态变量的值 - In a non static class ,How do I retain the value of a static variable used in a static method called in multiple different classes simultaneously 仅给出对象的字符串名称,如何访问非静态对象的静态方法? - How do I access a static method of an non static object given just the string name of the object? 当仅将类的类型名称作为字符串时,请使用类静态方法 - Use classes static method when you only have the type name of the class as a string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM