簡體   English   中英

如何實現動態返回模型類所有屬性的方法?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM