【问题标题】:Create class at runtime, serilize and de-serilize then cast to Interface froblem在运行时创建类,序列化和反序列化然后转换为接口问题
【发布时间】:2011-10-04 09:40:43
【问题描述】:

嗨,

我有以下代码:

public static object CreateTypedReport(string typeName, string inheritFrom)
{
    DirectoryInfo dirInfo;
    CSharpCodeProvider c = new CSharpCodeProvider();
    CompilerParameters cp = new CompilerParameters();

    foreach (Assembly asm in System.AppDomain.CurrentDomain.GetAssemblies())
    {
        if(!asm.FullName.StartsWith("ReportAssembly, Version=0.0.0.0"))
            cp.ReferencedAssemblies.Add(asm.Location);
    }

    cp.CompilerOptions = "/t:library";
    cp.GenerateInMemory = true;

    dirInfo = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\MyApp\\ReportAssemblies\\");

    if (!dirInfo.Exists)
        dirInfo.Create();

    cp.OutputAssembly = dirInfo.FullName + typeName + "Assembly";
    cp.ReferencedAssemblies.Add(typeof(XtraReport).Assembly.Location);

    //cp.OutputAssembly = typeName + "Assembly";

    StringBuilder sb = new StringBuilder("");

    sb.Append("using System;\n");
    sb.Append("using MyNamespace.UI;\n");

    sb.Append("namespace TypedReports { \n");
    sb.Append("public class " + typeName + " : " + inheritFrom + "{ \n");
    sb.Append("} \n");
    sb.Append("}\n");

    CompilerResults cr = c.CompileAssemblyFromSource(cp, sb.ToString());

    if (cr.Errors.Count > 0)
    {
        MessageBox.Show("ERROR: " + cr.Errors[0].ErrorText, "Error evaluating cs code", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return null;
    }

    return cr.CompiledAssembly.CreateInstance("TypedReports." + typeName);
}

这将基于typeNameinheritFrom 参数创建一个类,然后最终创建并返回一个对象。 inheritFrom 将指向实现IMyInterface 的类。

如果需要,可以将此对象转换为 IMyInterface

当我们随后序列化和反序列化这个对象时,我们将无法再将其转换为IMyInterface

为什么?我该如何解决?

【问题讨论】:

    标签: class inheritance interface runtime


    【解决方案1】:

    问题在于对象的序列化和反序列化。当它被改变时,它工作得很好。解决方案在第三方产品中,所以我不能在这里发布。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多