【问题标题】:Use classes static method when you only have the type name of the class as a string当您只有类的类型名称作为字符串时使用类静态方法
【发布时间】:2015-04-08 11:19:44
【问题描述】:

我想知道当你只通过它的字符串值知道类名时是否可以使用类方法。

假设我有一个类,在类中我有一个静态方法,例如

public class SomeClass 
{
    public static string Do()
    {
         //Do stuff
    }
}

当使用类时,我想要类似的东西

string str = (GetType(SomeClass)).Do();

当使用方法时,我想将类的名称作为字符串给出,就像我想将 SomeClass 作为字符串一样。

【问题讨论】:

标签: c# reflection types casting static


【解决方案1】:
var t = Type.GetType("MyNamespace.SomeClass");
var m = t.GetMethod("Do");

m.Invoke(null, new object[] { /* Any arguments go here */ });

【讨论】:

  • 当我尝试这个时,甚至 Type t = Type... GetMethod 似乎没有定义。
【解决方案2】:

使用Type.GetMethod获取方法的方法信息对象,然后调用MethodInfo.Invoke执行。对于静态方法,将 null 作为第一个参数(对象值)传递:

Type type = typeof(SomeClass);
type.GetMethod("Do").Invoke(null, null);

如果在编译时不知道类名,也可以使用object.GetTypeType.GetTypeAssembly.GetType在运行时获取类型对象(取决于你有什么信息可用)。然后,您可以按照相同的方式使用它:

Type type = someObject.GetType(); // or Type.GetType("SomeTypeName");
type.GetMethod("Do").Invoke(null, null);

为了安全起见,请确保检查GetMethod 是否确实返回了一个方法,这样您就可以确认该方法存在于该类型上。

【讨论】:

  • Op 只在运行时知道类名。
  • 如果 OP 在编译时知道的足够多,可以写typeof(SomeClass),他们还不如写SomeClass.Do()
  • @Asad 我认为戳误读了这个问题,就好像 OP 在编译时知道类但不知道方法。
  • 感谢您的更正,我更新了我的答案以反映这一点。
  • @poke Visual Studio 找不到 Type 类型的定义 GetMethod。我很困惑。
【解决方案3】:

您将不得不在整个过程中使用反射;例如:

object result = Type.GetType(typeName).GetMethod(methodName).Invoke(null, args);

【讨论】:

    猜你喜欢
    • 2016-06-18
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多