开发者

c# string to class from which I can call functions

on initialize a class by string variable in c#? I already found out how to create an class using a string

so what I already have is:

Type type = Type.GetType("project.start");
var class = Activator.CreateInstance(type);

what I want to do is call a function on this class for example:

class.foo();

is this possi开发者_如何学Goble? and if it is how?


Type yourType = Type.GetType("project.start");
object yourObject = Activator.CreateInstance(yourType);

object result = yourType.GetMethod("foo")
                        .Invoke(yourObject, null);


If you can assume that the class implements an interface or base class that exposes a Foo method, then cast the class as appropriate.

public interface IFoo
{
   void Foo();
}

then in your calling code you can do:

var yourType = Type.GetType("project.start");
var yourObject = (IFoo)Activator.CreateInstance(yourType);

yourType.Foo();


It is possible but you will have to use reflection or have class be cast as the proper type at runtime..

Reflection Example:

type.GetMethod("foo").Invoke(class, null);


Activator.CreateInstance returns a type of object. If you know the type at compile time, you can use the generic CreateInstance.

Type type = Type.GetType("project.start");
var class = Activator.CreateInstance<project.start>(type);


var methodInfo = type.GetMethod("foo");
object result  = methodInfo.Invoke(class,null);

The second argument to the Invoke method are the method parameters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜