簡體   English   中英

如何映射泛型類的屬性?

[英]How to map the properties of a generic class?

我正在用C#在我們的桌面軟件和客戶端api之間建立接口。 這個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)

等等...有人有什么聰明的主意嗎?

經過一番修補后,下面的代碼可以實現我想要的功能:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM