2014-11-12 3 views
0

나는 codedom을 사용하여 .cs 파일을 컴파일하고 invokemember을 통해 메소드를 추출합니다. 어떻게 그 방법으로 가치를 얻을 수 있습니까? 예를 들면 : 내가코드 결과 결과 함수에서 반환 값 얻기

여기 내 코드

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); 

의 방법에서 생성 된 webcontrol를 얻을 싶어 여기에 내 invokerteks.cs

namespace dinamis 
    { 
public class halo 
{ 
    private void halodunia() 
    { 
     System.Console.WriteLine("Hello World!!"); 

    } 
} 

}

날를 제공 할 수 있습니다 이 문제에 대한 자습서 링크가 있습니까?

+0

메서드에서 원하는 것을 반환하면 'InvokeMember()'에서 반환됩니다. – svick

답변

0

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 항상 반환하고 object의 인스턴스가 그래서 당신이 캐스팅 할 필요가 당신의 원하는 유형. 여기서는 잘못된 캐스트를주의하십시오.

+0

해결책 주셔서 감사합니다. –