简体   繁体   English

通过字符串获取静态类

[英]Get static class by string

Type.GetType("System.Windows.Forms.MessageBox")
    .GetMethod("Show", new Type[] { Type.GetType("System.String") })
    .Invoke(null, new object[] { "test" });

I'm trying invoke the MessageBox.Show("test") method, using only string values for class and method names. 我正在尝试仅使用类和方法名称的字符串值来调用MessageBox.Show("test")方法。 However, I cannot get the type of MessageBox by its name. 但是,我无法通过其名称来获取MessageBox的类型。

Any idea? 任何想法?

You need to specify the full name of the assembly. 您需要指定程序集的全名。
(it's located in the GAC - If you have win 7 you can see the assemblies in: %windir%\\assembly): (它位于GAC中-如果您赢了7,则可以在以下位置看到程序集:%windir%\\ assembly):

    Type t = Type.GetType("System.Windows.Forms.MessageBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
    var method = t.GetMethod("Show", new Type[] { Type.GetType("System.String") });
    method.Invoke(null, new object[] { "test" });
        string type = typeof(MessageBox).AssemblyQualifiedName;

        Type.GetType(type).GetMethod("Show", new Type[] { Type.GetType("System.String") }).Invoke(null, new object[] { "test" });

Ok everybody, the AssemblyQualifiedName works. 好的,大家好, AssemblyQualifiedName有效。

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

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