开发者

Create class at runtime, serilize and de-serilize then cast to Interface froblem

开发者 https://www.devze.com 2023-04-10 05:41 出处:网络
Hi, I have the following code : public static object CreateTypedReport(string typeName, string inheritFrom)

Hi,

I have the following code :

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

This will create a class based on the typeName and inheritFrom parameters and then finally an object will be created and returned. inheritFr开发者_如何学JAVAom will point at a class that implements IMyInterface.

It's possible to cast this object to a IMyInterface if it's needed.

When we then serialize and de-serialize this object we will not be able to cast it to IMyInterface anymore?

Why? And how could I solve it?


The problem was in the serialization och deserialization of the object. When this was changed it worked great. The solution is in a third party product so I can´t post it here.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号