简体   繁体   中英

How to map the properties of a generic class?

I'm building an interface in C# between our desktop software and a client's api. There a lot of endpoints in this api, but they all do very similar things. I'm tasked with writing code that will, given an object (let's say a User), POST that object to the api correctly. I could write a method for each endpoint, but in the interests of DRYness, I'm trying to figure out how to write a method that will take any of the objects I might pass to it, and construct a proper POST request using that. Here's some pseudo-code:

Accept User object
Pass to POST method
public POST method (T Resource)
{
    Get Resource name
    Get Resource properties
    foreach (Property in Resource)
    {
        Add Property name and value to request parameters
    }
    return configured request
}
PROFIT

The actual code I've come up with is this (this might be crappy):

public class POST
{
    public IRestResponse Create<T>(RestClient Client, T Resource, string Path)
    {
        IRestResponse Resp = null;
        RestRequest Req = Configuration.ConfigurePostRequest(Path);
        string ResourceName = Resource.GetType().GetProperties()[0].ReflectedType.Name; (this actually gives me what I need)
        string PropertyName = "";
        foreach (object property in Resource.GetType().GetProperties())
        {
            PropertyName = property.GetType().GetProperty("Name").ToString();
            Req.AddParameter(String.Format("{0}[{1}]", ResourceName.ToLower(), PropertyName.ToLower()), Resource.GetType().GetProperty(PropertyName).GetValue(PropertyName));
        }
        return Resp;
    }
}

I can clarify if this is gobbledegook, but each parameter should look like:

Req.AddParameter("user[name]", user.name)

Etc... Anyone have any clever ideas?

After some tinkering, here is the code that does what I want it to do:

public class POST
{
    public IRestResponse Create<T>(RestClient Client, T Resource, string Path)
    {
        IRestResponse Resp = null;
        RestRequest Req = Configuration.ConfigurePostRequest(Path);
        foreach (var property in Resource.GetType().GetProperties())
        {
            Req.AddParameter(String.Format("{0}[{1}]", Resource.GetType().Name.ToString().ToLower(), property.Name), Resource.GetType().GetProperty(property.Name).GetValue(Resource, null));
        }
        return Resp;
    }
}

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