[英]How can I implement a method to dynamically return all properties of a model class?
在我当前正在工作的项目上,这种情况下,我们必须调用一些实际上需要数百个参数的外部服务。
对于每种类型的请求,我们都有一个模型类,其类似于下面的内容(我们希望为这些参数列表提供一个静态类,因为数据的正确性至关重要,因此在编译时具有所有必填字段是必须的):
public class Model1
{
public int property1 { get; set; }
public string property2 { get; set; }
...
public string property900 { get; set; }
}
问题是,您不能简单地将其序列化为
<file>
<property1>1</property1>
<property2>Two</property2>
...
<property900>Nine hundred</property900>
</file>
因为该服务需要像这样的东西
<file>
<someConstantData>Metadata about the message</someConstantData>
<propertyList>
<property1>1</property1>
<property2>Two</property2>
...
<property900>Nine hundred</property900>
</propertyList>
</file>
现在,挑战在于我们如何将模型类序列化为上述XML? 在简单模型的情况下,我认为拥有需要使用它的所有类来实现手动返回Dictionary的方法的接口就可以解决问题。 如
return new Dictionary
{ pr1.ToKeyValuePair(), pr2.ToKeyValuePair(),... pr10.ToKeyValuePair() }
但是对于如此长的模型,这是毫无疑问的,所以我想到的另一种解决方案是在运行时创建一个Func,该Func使用反射GetValue()返回所有属性及其值,然后每次在模型中返回数据是必需的,只需在实例上调用它即可。 但是,我在这里读到,使用GetValue比标准访问属性要慢得多,对于我的企业应用程序,这可能意味着显着的速度下降。
您是否还有其他想法可以克服这一挑战?
过去对我有帮助:
public override string SaveObjectToFile(string folder, string file, object o)
{
string filename = Path.Combine(folder, string.Format("{0}{1}", file, FileExtension));
try
{
using (StreamWriter writer = new StreamWriter(filename, append: false))
{
new XmlSerializer(o.GetType()).Serialize(writer, o);
writer.Close();
}
}
catch (Exception ex)
{
Trace.TraceError("Unable to serialize object " + ex.Message);
}
return filename;
}
这会为您输出正确的XML吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.