C# 从codedom结果的方法获取返回值
我已经使用codedom编译了.cs文件,并通过invokemember提取了它的方法。但是我怎样才能从这个方法中得到一个值呢?例如:我想获取在方法中创建的webcontrol 这是我的密码C# 从codedom结果的方法获取返回值,c#,reflection,codedom,C#,Reflection,Codedom,我已经使用codedom编译了.cs文件,并通过invokemember提取了它的方法。但是我怎样才能从这个方法中得到一个值呢?例如:我想获取在方法中创建的webcontrol 这是我的密码 string[] filepath = new string[1]; filepath[0] = @"C:\Users\xxxx\Documents\Visual Studio 2010\Projects\xxx\xx\invokerteks.cs"; CodeDo
string[] filepath = new string[1];
filepath[0] = @"C:\Users\xxxx\Documents\Visual Studio 2010\Projects\xxx\xx\invokerteks.cs";
CodeDomProvider cpd = new CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("System.dll");
cp.ReferencedAssemblies.Add("System.Web.dll");
cp.GenerateExecutable = false;
CompilerResults cr = cpd.CompileAssemblyFromFile(cp, filepath);
if (true == cr.Errors.HasErrors)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
{
sb.Append(ce.ToString());
sb.Append(System.Environment.NewLine);
}
throw new Exception(sb.ToString());
}
Assembly invokerAssm = cr.CompiledAssembly;
Type invokerType = invokerAssm.GetType("dynamic.hello");
object invokerInstance = Activator.CreateInstance(invokerType);
invokerType.InvokeMember("helloworld", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic, null, invokerInstance, null);
这是我的invokerteks.cs
}
您能为我提供有关此问题的链接教程吗?InvokeMember将返回该方法返回的任何内容。由于helloworld方法返回时为void,因此不会返回任何内容。为了获得一些信息,请定义返回类型并像往常一样调用:
public class Hello
{
private int helloworld()
{
return new Random().NextInt();
}
}
这可以称为:
var type = typeof(Hello);
int value = (int)type.InvokeMember("helloworld", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic, null, invokerInstance, null);
InvokeMember始终返回对象的名称和实例,所以您必须强制转换为所需的类型。注意此处的无效强制转换。只需从方法中返回您想要的任何内容,它将从InvokeMember中返回。
var type = typeof(Hello);
int value = (int)type.InvokeMember("helloworld", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic, null, invokerInstance, null);