[英]Create a property and its type dynamically using propertydescriptor
我有一堂課,將有2個屬性
public class PropertyBag
{
public string PropertyName {get;set;}
public object PropertyValue {get;set;}
}
因此,此“ PropertyValue”屬性可以保存任何原始數據類型,例如int,datetime,string等。
我正在從具有嵌套元素的自定義配置文件中讀取設置。 像這樣:
<Workspace name="ws1">
<property name="version" type="decimal"> 1.3 </property>
<property name="datetime" type="datetime"> 10-10-2015 </property>
<property name="mainwindowlocation" type="string"> 10 300 850 </property>
...more nested elements...
</Workspace>
我希望能夠基於配置文件中的值動態設置“ PropertyValue”屬性的類型。 一位同事提到了PropertyDescriptors / TypeDescriptors / dynamic。 有具體實施細節的建議嗎?
謝謝
您可以簡單地使用switch語句根據類型值來解析值。
var properties = XDocument.Load("XMLFile2.xml").Descendants("property").Select(p =>
{
string name = p.Attribute("name").Value;
string type = p.Attribute("type").Value;
string value = p.Value;
PropertyBag bag = new PropertyBag();
bag.PropertyName = name;
switch (type)
{
case "decimal":
bag.PropertyValue = Decimal.Parse(value);
break;
case "datetime":
bag.PropertyValue = DateTime.Parse(value);
break;
default:
bag.PropertyValue = value;
break;
}
return bag;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.