【问题标题】:c# string to class from which I can call functionsc#字符串到我可以从中调用函数的类
【发布时间】:2023-04-08 04:24:01
【问题描述】:
【问题讨论】:
标签:
c#
activator
createinstance
【解决方案1】:
Type yourType = Type.GetType("project.start");
object yourObject = Activator.CreateInstance(yourType);
object result = yourType.GetMethod("foo")
.Invoke(yourObject, null);
【解决方案2】:
如果您可以假设该类实现了公开 Foo 方法的接口或基类,则适当地转换该类。
public interface IFoo
{
void Foo();
}
然后在你的调用代码中你可以这样做:
var yourType = Type.GetType("project.start");
var yourObject = (IFoo)Activator.CreateInstance(yourType);
yourType.Foo();
【解决方案3】:
这是可能的,但您必须使用反射或在运行时将 class 强制转换为正确的类型..
反射示例:
type.GetMethod("foo").Invoke(class, null);
【解决方案4】:
Activator.CreateInstance 返回object 的类型。如果您在编译时知道类型,则可以使用泛型 CreateInstance。
Type type = Type.GetType("project.start");
var class = Activator.CreateInstance<project.start>(type);
【解决方案5】:
var methodInfo = type.GetMethod("foo");
object result = methodInfo.Invoke(class,null);
Invoke 方法的第二个参数是方法参数。