如何映射泛型class的属性?

How to map the properties of a generic class?

我正在用 C# 在我们的桌面软件和客户的 api 之间构建一个接口。 api 中有很多端点,但它们都做非常相似的事情。我的任务是编写代码,在给定一个对象(假设是一个用户)的情况下,POST 该对象正确地指向 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)

等等...大家有什么妙招吗?

经过一些修改,这里是执行我想要它执行的操作的代码:

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