我正在尝试使用 System.Xml.Serialization.XmlSerializer 来序列化动态加载(和编译的类)。如果我将有问题的类构建到主程序集中,一切都会按预期进行。但是,如果我从动态加载的程序集中编译和加载该类,XmlSerializer 会引发异常。
我做错了什么?
我创建了以下 .NET 3.5 C# 应用程序来重现该问题:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.Reflection;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
public class StaticallyBuiltClass
{
public class Item
{
public string Name { get; set; }
public int Value { get; set; }
}
private List<Item> values = new List<Item>();
public List<Item> Values { get { return values; } set { values = value; } }
}
static class Program
{
static void Main()
{
RunStaticTest();
RunDynamicTest();
}
static void RunStaticTest()
{
Console.WriteLine("-------------------------------------");
Console.WriteLine(" Serializing StaticallyBuiltClass...");
Console.WriteLine("-------------------------------------");
var stat = new StaticallyBuiltClass();
Serialize(stat.GetType(), stat);
Console.WriteLine();
}
static void RunDynamicTest()
{
Console.WriteLine("-------------------------------------");
Console.WriteLine(" Serializing DynamicallyBuiltClass...");
Console.WriteLine("-------------------------------------");
CSharpCodeProvider csProvider = new CSharpCodeProvider(new Dictionary<string, string> { { "CompilerVersion", "v3.5" } });
CompilerParameters csParams = new System.CodeDom.Compiler.CompilerParameters();
csParams.GenerateInMemory = true;
csParams.GenerateExecutable = false;
csParams.ReferencedAssemblies.Add("System.dll");
csParams.CompilerOptions = "/target:library";
StringBuilder classDef = new StringBuilder();
classDef.AppendLine("using System;");
classDef.AppendLine("using System.Collections.Generic;");
classDef.AppendLine("");
classDef.AppendLine("public class DynamicallyBuiltClass");
classDef.AppendLine("{");
classDef.AppendLine(" public class Item");
classDef.AppendLine(" {");
classDef.AppendLine(" public string Name { get; set; }");
classDef.AppendLine(" public int Value { get; set; }");
classDef.AppendLine(" }");
classDef.AppendLine(" private List<Item> values = new List<Item>();");
classDef.AppendLine(" public List<Item> Values { get { return values; } set { values = value; } }");
classDef.AppendLine("}");
CompilerResults res = csProvider.CompileAssemblyFromSource(csParams, new string[] { classDef.ToString() });
foreach (var line in res.Output)
{
Console.WriteLine(line);
}
Assembly asm = res.CompiledAssembly;
if (asm != null)
{
Type t = asm.GetType("DynamicallyBuiltClass");
object o = t.InvokeMember("", BindingFlags.CreateInstance, null, null, null);
Serialize(t, o);
}
Console.WriteLine();
}
static void Serialize(Type type, object o)
{
var serializer = new XmlSerializer(type);
try
{
serializer.Serialize(Console.Out, o);
}
catch(Exception ex)
{
Console.WriteLine("Exception caught while serializing " + type.ToString());
Exception e = ex;
while (e != null)
{
Console.WriteLine(e.Message);
e = e.InnerException;
Console.Write("Inner: ");
}
Console.WriteLine("null");
Console.WriteLine();
Console.WriteLine("Stack trace:");
Console.WriteLine(ex.StackTrace);
}
}
}
生成以下输出:
-------------------------------------
Serializing StaticallyBuiltClass...
-------------------------------------
<?xml version="1.0" encoding="IBM437"?>
<StaticallyBuiltClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Values />
</StaticallyBuiltClass>
-------------------------------------
Serializing DynamicallyBuiltClass...
-------------------------------------
Exception caught while serializing DynamicallyBuiltClass
There was an error generating the XML document.
Inner: The type initializer for 'Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterDynamicallyBuiltClass' threw an exception.
Inner: Object reference not set to an instance of an object.
Inner: null
Stack trace:
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o, XmlSerializerNamespaces namespaces)
at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o)
at Program.Serialize(Type type, Object o) in c:\dev\SerTest\SerTest\Program.cs:line 100
编辑:删除了一些无关的引用程序集
最佳答案
将 CompilerParameters.GenerateInMemory 更改为 false 即可。我不知道这是否是 XML 序列化过程的限制,但如果将程序集生成到磁盘上的临时位置不是问题,那么这将解决您的问题。
关于c# - XmlSerializer 在序列化动态加载的类型时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2492175/
鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende
我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("
我正在学习Rails,并阅读了关于乐观锁的内容。我已将类型为integer的lock_version列添加到我的articles表中。但现在每当我第一次尝试更新记录时,我都会收到StaleObjectError异常。这是我的迁移:classAddLockVersionToArticle当我尝试通过Rails控制台更新文章时:article=Article.first=>#我这样做:article.title="newtitle"article.save我明白了:(0.3ms)begintransaction(0.3ms)UPDATE"articles"SET"title"='dwdwd
在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee
如何在ruby中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL
我早就知道Ruby中的“常量”(即大写的变量名)不是真正常量。与其他编程语言一样,对对象的引用是唯一存储在变量/常量中的东西。(侧边栏:Ruby确实具有“卡住”引用对象不被修改的功能,据我所知,许多其他语言都没有提供这种功能。)所以这是我的问题:当您将一个值重新分配给常量时,您会收到如下警告:>>FOO='bar'=>"bar">>FOO='baz'(irb):2:warning:alreadyinitializedconstantFOO=>"baz"有没有办法强制Ruby抛出异常而不是打印警告?很难弄清楚为什么有时会发生重新分配。 最佳答案
我一直致力于让我们的Rails2.3.8应用程序在JRuby下正确运行。一切正常,直到我启用config.threadsafe!以实现JRuby提供的并发性。这导致lib/中的模块和类不再自动加载。使用config.threadsafe!启用:$rubyscript/runner-eproduction'pSim::Sim200Provisioner'/Users/amchale/.rvm/gems/jruby-1.5.1@web-services/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:105:in`co
我正在尝试在Ruby中复制Convert.ToBase64String()行为。这是我的C#代码:varsha1=newSHA1CryptoServiceProvider();varpasswordBytes=Encoding.UTF8.GetBytes("password");varpasswordHash=sha1.ComputeHash(passwordBytes);returnConvert.ToBase64String(passwordHash);//returns"W6ph5Mm5Pz8GgiULbPgzG37mj9g="当我在Ruby中尝试同样的事情时,我得到了相同sha
给定一个复杂的对象层次结构,幸运的是它不包含循环引用,我如何实现支持各种格式的序列化?我不是来讨论实际实现的。相反,我正在寻找可能会派上用场的设计模式提示。更准确地说:我正在使用Ruby,我想解析XML和JSON数据以构建复杂的对象层次结构。此外,应该可以将该层次结构序列化为JSON、XML和可能的HTML。我可以为此使用Builder模式吗?在任何提到的情况下,我都有某种结构化数据-无论是在内存中还是文本中-我想用它来构建其他东西。我认为将序列化逻辑与实际业务逻辑分开会很好,这样我以后就可以轻松支持多种XML格式。 最佳答案 我最
C#实现简易绘图工具一.引言实验目的:通过制作窗体应用程序(C#画图软件),熟悉基本的窗体设计过程以及控件设计,事件处理等,熟悉使用C#的winform窗体进行绘图的基本步骤,对于面向对象编程有更加深刻的体会.Tutorial任务设计一个具有基本功能的画图软件**·包括简单的新建文件,保存,重新绘图等功能**·实现一些基本图形的绘制,包括铅笔和基本形状等,学习橡皮工具的创建**·设计一个合理舒适的UI界面**注明:你可能需要先了解一些关于winform窗体应用程序绘图的基本知识,以及关于GDI+类和结构的知识二.实验环境Windows系统下的visualstudio2017C#窗体应用程序三.