获取对类的引用并仅从字符串值执行静态方法?
如何获取带有字符串的静态类的实例?
例子:
class Apple : IFruit { public static Apple GetInstance() { ... } private Apple() { } // other stuff } class Banana : IFruit { public static Banana GetInstance() { ... } private Banana() { } // other stuff } // Elsewhere in the code... string fruitIWant = "Apple"; IFruit myFruitInstance = [What goes here using "fruitIWant"?].GetInstance();
How can I get an instance of a static class with a string?
Example:
class Apple : IFruit { public static Apple GetInstance() { ... } private Apple() { } // other stuff } class Banana : IFruit { public static Banana GetInstance() { ... } private Banana() { } // other stuff } // Elsewhere in the code... string fruitIWant = "Apple"; IFruit myFruitInstance = [What goes here using "fruitIWant"?].GetInstance();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
请注意,在
Type.GetType
中,您需要使用程序集限定名称。Note that in
Type.GetType
you need to use the assembly-qualified name.这是一个完整的例子。只需传入要加载的类型的名称和要调用的方法的名称:
Here is a complete example. Just pass in the name of the type you want to load and the name of the method to invoke:
您可以这样做:
对于
ApplicationName
,您可以替换声明该类的名称空间。(经过测试并工作。)
You do like this:
For
ApplicationName
you substitute the namespace where the class is declared.(Tested and working.)
好吧,也许我收到了你的问题。
伪代码
编辑
应该可以工作..
OK, may be I got your question.
A pseudocode
EDIT
Should work..
虽然其他人给了你你所要求的东西,但这可能就是你想要的:
While the others give you what you asked for, this is probably what you want: