简体   繁体   中英

How can I implement a method to dynamically return all properties of a model class?

On the project I am currently working, there is this situation in which we have to call some external services that require literally hundreds of parameters.

We have a model class for each type of request, with something similar to what we have below (we want to have a static class for these lists of parameters because the correctness of data is vital and thus having all the required fields at compile time is a must):

public class Model1
{
     public int property1 { get; set; }
     public string property2 { get; set; }
     ...
     public string property900 { get; set; }
}

Thing is, you cannot simply serialize it to

<file>
    <property1>1</property1>
    <property2>Two</property2>
    ...
    <property900>Nine hundred</property900>
</file>

because that service requires it as something like this

<file>
    <someConstantData>Metadata about the message</someConstantData>
    <propertyList>
        <property1>1</property1>
        <property2>Two</property2>
        ...
        <property900>Nine hundred</property900>
    </propertyList>
</file>

Now, the challenge is how do we serialize our model class into the above XML? In the case of simple models, I am thinking that having an interface that requires all the classes that use it to implement a method that manually returns a Dictionary would do the trick. As in

return new Dictionary 
{ pr1.ToKeyValuePair(), pr2.ToKeyValuePair(),... pr10.ToKeyValuePair() }

But in the case of such long models, this is out of question, so another solution I thought of is to create at runtime a Func that returns all the properties and their values using reflection GetValue() and then each time the data in the model is needed, just call it on an instance. However, I've read here that using GetValue is considerably slower than standard access to a property, and in the case of my enterprise application this could mean significant slowdowns.

Do you have any other ideas how this challenge could be overcome?

This has helped me in the past:

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;
}

Does this output the correct XML for you?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM