我有一些由其他人提供的用于序列化的类。这些类由许多具有默认值的参数构成。我需要使用其他默认值来启动它们。它是这样实现的:
public class Header
{
public class SubHeader1
{
[XmlElement("paramone")]
public string param1{get;set;}
[XmlElement("paramtwo")]
public string param2{get;set;}
[XmlElement("paramthree")]
public string param3{get;set;}
[XmlElement("paramfour")]
public string param4{get;set;}
public SubHeader1()
{
param1 = "theirdefault";
param2 = "theirdefault";
param3 = "theirdefault";
param4 = "theirdefault";
}
}
public class SubHeader2
{
[XmlElement("paramone")]
public string param1{get;set;}
[XmlElement("paramtwo")]
public string param2{get;set;}
public SubHeader1()
{
param1 = "theirdefault";
param2 = "theirdefault";
}
}
Public class SubHeader3
{
public class SubSubHeader
{
[XmlElement("paramone")]
public string param1{get;set;}
[XmlElement("paramtwo")]
public string param2{get;set;}
[XmlElement("paramthree")]
public string param3{get;set;}
[XmlElement("paramfour")]
public string param4{get;set;}
...
[XmlElement("paramtwentyfive")]
pulic string param25{get;set;}
public SubHeader1()
{
param1 = "theirdefault";
param2 = "theirdefault";
param3 = "theirdefault";
param4 = "theirdefault";
...
param25 = "theirdefault";
}
}
[XmlElement("paramone")]
public string param1{get;set;}
[XmlElement("subsubheader")]
public SubSubHeader SSubHeader;
public SubHeader3()
{
SSubHeader = new SubSubHeader();
param1 = "theirdefault";
}
}
[XmlElement("subheaderone")]
public SubHeader1 SubHeaderOne;
[XmlElement("subheadertwo")]
public SubHeader2 SubHeaderTwo;
[XmlElement("subheaderthree")]
public SubHeader3 SubHeaderThree;
public Header()
{
SubHeaderOne = new SubHeader1();
SubHeaderTwo = new SubHeader2();
SubHeaderThree = new SubHeader3();
}
}
这就是每个继承类的标准。我还有一些其他信息需要启动,主要在子标题中。
我创建了自己的 SubHeader3 对象,并在他们的类中创建了一个构造函数(用于测试目的),该构造函数接受该对象。我试图通过这样的泛型用我的更新默认值
public static void MergeWith<T>(this T primary, T secondary) {
foreach (var pi in typeof(T).GetProperties()) {
var priValue = pi.GetGetMethod().Invoke(primary, null);
var secValue = pi.GetGetMethod().Invoke(secondary, null);
if (priValue == null || (pi.PropertyType.IsValueType && priValue == Activator.CreateInstance(pi.PropertyType))) {
pi.GetSetMethod().Invoke(primary, new object[]{secValue});
}
}
}
但这仅适用于 SubHeader3 类中的值,不适用于嵌套的 SubSubClass。这是实现这一目标的最佳方法吗?如何在编译器安全的情况下让它覆盖子类。还是我以错误的方式接近这个?