gpt4 book ai didi

c# - 如何将xml反序列化为继承对象?

转载 作者:行者123 更新时间:2023-11-30 22:31:15 25 4
gpt4 key购买 nike

我有以下 xml,代表两种类型的插件,FilePlugin 和 RegsitryPlugin:

<Client>
<Plugin Type="FilePlugin">
<Message>i am a file plugin</Message>
<Path>c:\</Path>
</Plugin>
<Plugin Type="RegsitryPlugin">
<Message>i am a registry plugin</Message>
<Key>HKLM\Software\Microsoft</Key>
<Name>Version</Name>
<Value>3.5</Value>
</Plugin>
</Client>

我想将 xml 反序列化为对象。如您所见,“消息”元素在 FilePlugin 和 RegistryPlugin 中重复自身,我为此使用继承:

    abstract class Plugin
{
private string _message;
protected Plugin(MISSING conf)
{
// here i need to set my private members like:
// Message = MISSING.Message;
}
}

class FilePlugin : Plugin
{
private string _path;
public FilePlugin(MISSING config)
: base(config)
{
// Here i need to set my private members like:
// _path = config.Path;
}
}

class RegistryPlugin : Plugin
{
private string _key;
private string _name;
private string _value;
public RegistryPlugin(MISSING config)
: base(config)
{
// Here i need to set my private members like:
// _key = config.Key;
// _key = config.Name;
// _key = config.Value;
}
}
}

我需要以某种方式反序列化 xml,而不是根据 PluginType 元素来决定创建哪个实例:IE:如果它是用 xml 编写的,则 Type=FilePlugin 比我需要创建的

Plugin p1 = new FilePlugin(conf);

如果它是在 xml 中编写的,那么我需要创建 Type=RegistryPlugin

Plugin p2 = new RegistryPlugin(conf);

请按照我在代码中的注释进行操作,以了解缺失的部分。谢谢

最佳答案

创建您自己的反序列化器也不难。这是我的解决方案:

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Xml.Linq;
using System.Reflection;
using System.Text;

namespace WindowsFormsApplication1
{
public abstract class Plugin
{
public string Type { get; set; }
public string Message { get; set; }
}

public class FilePlugin : Plugin
{
public string Path { get; set; }
}

public class RegsitryPlugin : Plugin
{
public string Key { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}

static class MyProgram
{
[STAThread]
static void Main(string[] args)
{
string xmlstr =@"
<Client>
<Plugin Type=""FilePlugin"">
<Message>i am a file plugin</Message>
<Path>c:\</Path>
</Plugin>
<Plugin Type=""RegsitryPlugin"">
<Message>i am a registry plugin</Message>
<Key>HKLM\Software\Microsoft</Key>
<Name>Version</Name>
<Value>3.5</Value>
</Plugin>
</Client>
";

Assembly asm = Assembly.GetExecutingAssembly();
XDocument xDoc = XDocument.Load(new StringReader(xmlstr));
Plugin[] plugins = xDoc.Descendants("Plugin")
.Select(plugin =>
{
string typeName = plugin.Attribute("Type").Value;
var type = asm.GetTypes().Where(t => t.Name == typeName).First();
Plugin p = Activator.CreateInstance(type) as Plugin;
p.Type = typeName;
foreach (var prop in plugin.Descendants())
{
type.GetProperty(prop.Name.LocalName).SetValue(p, prop.Value, null);
}

return p;
}).ToArray();

//
//"plugins" ready to use
//
}
}
}

关于c# - 如何将xml反序列化为继承对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9341432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com