Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何映射泛型类的属性?_C#_Rest_Restsharp - Fatal编程技术网

C# 如何映射泛型类的属性?

C# 如何映射泛型类的属性?,c#,rest,restsharp,C#,Rest,Restsharp,我正在用C语言在我们的桌面软件和客户端的api之间构建一个接口。这个api中有很多端点,但它们都做非常相似的事情。我的任务是编写代码,在给定对象(比如用户)的情况下,将该对象正确地发布到api。我可以为每个端点编写一个方法,但出于干燥的考虑,我试图找出如何编写一个方法,该方法将接收我可能传递给它的任何对象,并使用该方法构造一个适当的POST请求。下面是一些伪代码: Accept User object Pass to POST method public POST method (T Resou

我正在用C语言在我们的桌面软件和客户端的api之间构建一个接口。这个api中有很多端点,但它们都做非常相似的事情。我的任务是编写代码,在给定对象(比如用户)的情况下,将该对象正确地发布到api。我可以为每个端点编写一个方法,但出于干燥的考虑,我试图找出如何编写一个方法,该方法将接收我可能传递给它的任何对象,并使用该方法构造一个适当的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);
        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;
    }
}
公共类职位
{
公共IRestResponse创建(RestClient客户端、T资源、字符串路径)
{
iRestreponse Resp=null;
RestRequest Req=Configuration.ConfigurePostRequest(路径);
foreach(Resource.GetType().GetProperties()中的var属性)
{
Req.AddParameter(String.Format(“{0}[{1}]”),Resource.GetType().Name.ToString().ToLower(),property.Name),Resource.GetType().GetProperty(property.Name).GetValue(Resource,null));
}
返回响应;
}
}
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;
    }
}