最近在項目過程中碰到了一些問題:
背景程式會動態產生一些類對象, Silverlight 接收到這些類對象後 進行使用。
在實際編程過程中碰到了一個棘手問題。
[OperationContract]
public object Test()
{
StringBuilder cs = new StringBuilder();
cs.AppendLine("namespace Runtime");
cs.AppendLine("{");
//cs.AppendLine("using System.Data;");
cs.AppendLine("using System.Collections.Generic;");
cs.AppendLine("using System.Reflection;");
cs.AppendLine("using System.ComponentModel;");
cs.AppendLine("using System.Runtime.Serialization;");
cs.AppendLine("using System;");
cs.AppendLine("[Serializable]");
cs.AppendLine("public class TestData ");
cs.AppendLine(" ");
cs.AppendLine("{public int IDDD{get;set;}}}");
CompilerParameters options = new CompilerParameters();
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
options.ReferencedAssemblies.Add("system.dll");
options.ReferencedAssemblies.Add("system.Runtime.Serialization.dll");
Assembly assembly = Assembly.GetAssembly(base.GetType());
options.ReferencedAssemblies.Add(assembly.Location);
CompilerResults results = provider.CompileAssemblyFromSource(options, new string[] { cs.ToString() });
if (results.Errors.HasErrors)
{
throw new Exception(results.Errors[0].ErrorText);
}
object o = results.CompiledAssembly.CreateInstance("Runtime.TestData");
return o;
}
Silverlight 在訪問Test 的方法時會出異常: Not Found Method 錯誤。
後來發現是由於 在動態編譯的時候 是引用的 C#3.5 的System.dll,而在Silverlight中無法解析。
想到的方法是:引用Silverlight SDK的System.dll,動態編譯時間產生固定的DLL檔案,然後在Silverlight中 下載下來進行反射調用。
雖然該方法可以成功,但有很大的弊端:需要對WEB目錄設定可寫入權限,並且需要安裝Silverlight SDK。
不知道高手們 有其他的好方法嗎?