我需要调用静态类的方法。该类仅在运行时已知(它是一个 System.Type 变量)。我知道我的方法是在“MyObject”类中实现的。我如何调用这样的方法?下面的代码说明了我需要做的事情。它可能看起来有点变态,但我发誓我会用它来实现良好的目的,并且不会让宇宙崩溃。
public class MyObject
{
public static string ReturnUsefulStuff()
{
return "Important result.";
}
}
public class MyChildObject: MyObject
{
// Hey! I know about ReturnUsefulStuff() method too!
}
public class App
{
public void Main()
{
// The following type isn't supposed to be known at compile time.
// Except that it will always be MyObject type or its descendent.
Type TypeOfMyObject = typeof(MyChildObject);
// My erotic fantasy below. That line doesn't actually work for static methods
string Str = (TypeOfMyObject as MyObject).ReturnUsefulStuff();
// I know that type has this method! Come on, let me use it!
MessageBox.Show(Str);
}
}
在 Delphi 中,这可以通过声明来实现
// ...
// interface
Type TMyObjectClass = class of TMyObject;
// ...
// implementation
ClassVar := TMyChildObject;
Str := TMyObjectClass(ClassVar).ReturnUsefulStuff();
这要归功于 Delphi 的“类”结构。编译器知道TMyObject具有“ReturnUsefulStuff”并且TMyChildObject是从它派生的,并且它还具有对ClassVar中的类的引用。这是所需要的一切。 C# 没有“类”的概念,它只有一个 System.Type(很难)统治所有这些。 有什么建议么?我会被迫使用各种丑陋的反射技术吗?
最佳答案
您的代码中有一个误解:
Delphi 有“类”的概念,这意味着字段/变量可以保留类本身的引用。 .net clr没有这个概念。在 .Net 中,运行时您可以查询有关特定类型的信息。当您调用 obj.GetType() 时,您将获得一个包含有关类型信息的 Type 对象。然而,Type
并不像 Delphi 中那样是类本身,它只是一个带有一堆信息的常规对象。
这就是为什么这在 .net 中是非法的:
// TypeOfMyObject is a object of the class Type, which MyObject does not inherit.
(TypeOfMyObject as MyObject).ReturnUsefulStuff();
所以,是的,在这种情况下你必须使用反射。
var method = typeOfMyObject.GetMethod("ReturnUsefulStuff",
BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
var result = method.Invoke(null, null);
关于.net - 如何调用仅在运行时已知的类的静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12040273/