0
私はこのコードをうまく使っています 私は '許可'という名前のxmlに別の要素を追加したいのですが質問です。要素を許可すると 'True'または 'False'の値を取得できます。反射のオブジェクトを変換する方法
public bool Allow { get; set; }
それを変換する可能性がある:私は、プラグインは、追加のプロパティを持つことになりますつまり、私のプラグインクラスのboolean型プロパティに変換したいですか?
コード例はありますか? 使用<Allow>
真</Allow>
ない<Allow>
真</Allow>
:
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へ
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 [email protected]"
<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
//
}
}
}
ありがとう、本当に真ではなく真を使用する理由を詳しく教えていただけますか? – user829174
実際、私はこの文を「bool b = true」と考えて書きました。私は100%確実ではない。たぶん真実でもあります。試して見てください。 –