如何在反射中转换对象

时间:2012-02-18 16:12:12

标签: c# reflection

我有这段代码工作正常, 我的问题是,如果我想在名为“允许”的xml中添加另一个元素。 Allow Element可以获得'True'或'False'的值。我想将它转换为我的Plugin类中的布尔属性,这意味着插件将具有附加属性:

public bool Allow { get; set; }

是否有可能转换它?

你能给出一个代码示例吗?

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
            //
        }
    }
}

1 个答案:

答案 0 :(得分:2)

更改

foreach (var prop in plugin.Descendants())
{
    type.GetProperty(prop.Name.LocalName).SetValue(p, prop.Value, null);
}

foreach (var prop in plugin.Descendants())
{
    var pi = type.GetProperty(prop.Name.LocalName);
    object newVal = Convert.ChangeType(prop.Value, pi.PropertyType);
    pi.SetValue(p, newVal, null);
}

<强> PS: 使用<Allow> true </Allow>而非<Allow> True </Allow>