如何映射泛型类的属性?

时间:2017-06-20 20:03:29

标签: c# rest restsharp

我在桌面软件和客户端api之间用C#构建界面。这个api中有很多端点,但它们都做了非常相似的事情。我的任务是编写代码,给定一个对象(让我们说一个用户),将该对象正确地发布到api。我可以为每个端点编写一个方法,但为了DRYness的利益,我试图弄清楚如何编写一个方法来接受我可能传递给它的任何对象,并使用它构造一个正确的POST请求那。这是一些伪代码:

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

我提出的实际代码就是这个(这可能很糟糕):

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

我可以澄清这是否是gobbledegook,但每个参数应如下所示:

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

等......任何人都有任何聪明的想法?

1 个答案:

答案 0 :(得分:0)

经过一些修补,这里的代码可以完成我想要它做的事情:

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