2015-11-18 15 views
1

對不起,我是使用CodeDom進行編程的新手,我遇到了這個我無法解決的問題。想着如果你們中的一些人知道解決方案。C#CodeDom:在字符串代碼中作爲參數的自定義類

我有一個類文件中的下面的代碼:

public class AnotherCustomClass { 
    public string Employer { get; set; } 
    public DateTime? DateOfHire { get; set; } 
} 

public class CustomClass { 
    public int X { get; set; } 
    public int Y { get; set; } 
    public AnotherCustomClass[] YetAnother { get; set; } 
} 

public void DoSomething() 
{ 
    string expression = @"using System; 
    namespace MyNamespace { 
     public class MyClass { 
      public static int DoStuff(CustomClass myCustomClass) { 
       return myCustomClass.X + myCustomClass.Y; 
      } 
     } 
    }"; 

    CSharpCodeProvider provider = new CSharpCodeProvider(); 
    CompilerParameters assemblies = new CompilerParameters(new[] { "System.Core.dll" }); 
    CompilerResults results = provider.CompileAssemblyFromSource(assemblies, expression); 
    Type temporaryClass = results.CompiledAssembly.GetType("MyNamespace.MyClass"); 
    MethodInfo temporaryFunction = temporaryClass.GetMethod("DoStuff"); 
    CustomClass data = new CustomClass() { X = 1, Y = 2 }; 
    object result = temporaryFunction.Invoke(null, new object[] { data }); 
    return result; 
} 

我想輸入數據(自定義創建的類,其具有內部另一自定義類的數組)變量作爲參數在DoStuff功能,我一直有錯誤。有沒有辦法解決這個問題?

+2

對不起,你的問題是不明確的。請說明你想要用它做什麼。 –

+0

好,所以你想編譯這個?這就是問題所在?添加一些額外的信息。例如'CustomClass'的位置以及你被拖拽的位置? –

+0

[是否可以動態編譯和執行C#代碼片段?](http://stackoverflow.com/questions/826398/is-it-possible-to-dynamically-compile-and-execute-c-sharp -code-fragments) –

回答

0

的多個錯誤,改變這樣:

string expression = @"using System; 
namespace MyNamespace { 
    public class MyClass { 
     public static int DoStuff(CustomClass myCustomClass) { 
      return myCustomClass.X + myCustomClass.Y; 
     } 
    } 

    public class CustomClass 
    { 
     public int X; 
     public int Y; 
     public CustomClass(int x, int y) { X = x; Y = y; } 
    } 
}"; 

CSharpCodeProvider provider = new CSharpCodeProvider(); 
CompilerParameters assemblies = new CompilerParameters(new string[] { "System.dll" }); 
CompilerResults results = provider.CompileAssemblyFromSource(assemblies, expression); 
Type temporaryClass = results.CompiledAssembly.GetType("MyNamespace.MyClass"); 
Type parClass = results.CompiledAssembly.GetType("MyNamespace.CustomClass"); 
MethodInfo temporaryFunction = temporaryClass.GetMethod("DoStuff"); 
object mc = parClass.GetConstructor(new Type[] { typeof(int), typeof(int) }).Invoke(new object[]{1,2}); 
object result = temporaryFunction.Invoke(null, new object[] { mc }); 
+0

我想在這個答案中,你在運行時創建了新的「類」。我對麼?我需要輸入類,而不是在運行時創建它。雖然這可能有幫助。我再次更新了我的問題,謝謝你的迴應! –

+0

然後,您必須在編譯時添加對包含自定義類的dll的引用。就像system.dll一樣,添加myclass.dll(並從Realtime編譯代碼中刪除che聲明) – owairc