I need to invoke a method of a static class. This class in known only at runtime (it is a System.Type variable). I know that my method is implemented in class “MyObject”. How do I invoke such method? Code that illustrates what I need to do is below. It may look a bit perverted but I swear I’ll use this for good purposes and will not allow the Universe to implode.
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);
}
}
In Delphi, this can be achieved by declaring
// ...
// interface
Type TMyObjectClass = class of TMyObject;
// ...
// implementation
ClassVar := TMyChildObject;
Str := TMyObjectClass(ClassVar).ReturnUsefulStuff();
This works thanks to Delphi’s “class of” construct. Compiler is aware that TMyObject has “ReturnUsefulStuff” and TMyChildObject is derived from it, and also it has the reference to the class in ClassVar. It’s everything that is needed. C# doesn’t have the notion of “class of”, it only has The One System.Type that will (hardly) rule them all.
Any suggestions? Will I be forced to use all kinds of ugly Reflection techniques?
There is a misconception in your code:
Delphi has the concept of “class of”, which means that a field/variable can keep a reference for the class itself. The .net clr doesn’t have this concept. In .Net at runtime you can query for information about a specific type. When you call
obj.GetType()you get aTypeobject containing information about the type. However theTypeis not the class itself like in Delphi, it is just a regular object with a bunch of information.That’s why this is illegal in .net:
So, yes, in this case you must use reflection.