c#string to class,我可以从中调用函数

在c#中用字符串变量初始化一个类?我已经找到了如何使用字符串创建类 所以我已经拥有的是:
Type type = Type.GetType("project.start");
var class = Activator.CreateInstance(type);
我想要做的是在这个类上调用一个函数,例如:
class.foo();
这可能吗?如果是这样的话?     
已邀请:
Type yourType = Type.GetType("project.start");
object yourObject = Activator.CreateInstance(yourType);

object result = yourType.GetMethod("foo")
                        .Invoke(yourObject, null);
    
如果您可以假设该类实现了一个公开Foo方法的接口或基类,则根据需要强制转换该类。
public interface IFoo
{
   void Foo();
}
然后在你的调用代码中你可以做到:
var yourType = Type.GetType("project.start");
var yourObject = (IFoo)Activator.CreateInstance(yourType);

yourType.Foo();
    
这是可能的,但您必须使用反射或在运行时将
class
转换为正确的类型。 反思示例:
type.GetMethod("foo").Invoke(class, null);
    
Activator.CreateInstance
返回类型
object
。如果您在编译时知道类型,则可以使用通用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);
Invoke方法的第二个参数是方法参数。     

要回复问题请先登录注册