使用 属性 描述符动态创建 属性 及其类型
Create a property and its type dynamically using propertydescriptor
我有一个 class 有 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;
});
我有一个 class 有 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;
});