我需要创建一个通用解决方案来创建从 xsd 生成的类的实例。例如:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="PS">
<xs:complexType>
<xs:sequence>
<xs:element name="P" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="FXs" maxOccurs="1" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="FX" minOccurs="1">
<xs:complexType>
<xs:attribute name="asOfDate" type="xs:date" use="required" />
<xs:attribute name="currency" type="xs:string" use="required" />
<xs:attribute name="rate" type="xs:decimal" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="PName" type="xs:string" />
<xs:attribute name="currency" type="xs:string" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
当我从这个 xsd 运行时生成程序集时,它将具有 PS、PSP 和 PSFX 类。在这种情况下,我知道属性和期望的内容,因此 createinstance 和 getproperties 和 setvalue 将起作用。我知道投资组合将有一系列 PortfoliosPortfolio。
case "PS":
if (p== null)
p= myAssembly.CreateInstance(cls.FullName);
break;
case "PSP":
myClass = myAssembly.CreateInstance(cls.FullName);
myClass.GetType().GetProperty("PName").SetValue(myClass, dt.Rows[0]["PortfolioName"].ToString(), null);
myClass.GetType().GetProperty("currency").SetValue(myClass, dt.Rows[0]["Currency"].ToString(), null);
if (myClasses == null)
myClasses = Array.CreateInstance(myClass.GetType(), deals.Count());
myClasses.SetValue(myClass, l);
l++;
portfolio.GetType().GetProperty("P").SetValue(p, myClasses, null);
现在我想要一个通用的解决方案,它可以采用任何 xsd(不仅仅是上面的)并生成一个程序集。我已经生成了汇编,但现在我的问题是如何为不知道其中存在哪些属性的类动态分配属性?我的意思是我如何知道一个类在创建通用解决方案时正在使用另一个类的对象列表。因此,有一种方法可以获取实例和属性,而不是对类名和属性名进行硬编码。正如您从上面的代码片段中看到的那样,我将 a 数据集中的值分配给属性。计划是将值作为列名、属性名和父节点存储在数据库中。因此 P 节点中的 PName 属性将来自列名 Pname。我希望以这样一种方式进行设计,即我的代码中不会有任何硬编码。
对不起,请多多包涵,如果我说得不对,请告诉我。