Skip to main content
 首页 » 编程设计

c#之如何找出字典对象中键的值

2024年02月05日11softidea

我有这个 API 调用:

HttpResponse<string> response =  
    Unirest.get("https://wordsapiv1.p.mashape.com/words/" + word.Name) 
    .header("X-Mashape-Key", "xxxx") 
    .header("Accept", "application/json") 
    .asJson<string>(); 

这是 HttpResponse 的类:

public class HttpResponse<T> 
{ 
    public HttpResponse(HttpResponseMessage response); 
 
    public T Body { get; set; } 
    public int Code { get; } 
    public Dictionary<string, string> Headers { get; } 
    public Stream Raw { get; } 
} 

获取正文 (response.Body) 或代码没有问题,但我想做的是获取此 header :

[7] = {[X-RateLimit-requests-Remaining, 2498]} 

谁能告诉我如何检查返回的响应并找出 X-RateLimit-requests-Remaining 的值?

请您参考如下方法:

字典有一个叫做 indexer 的东西.您的索引器的数据类型是您的 Key 的数据类型( Dictionary<Key,Value> )。

索引器类似于属性 getter 和 setter,并且是这样实现的:

public TValue this[TKey index] 
{ 
    // this will return when being called e.g. 'var x = dictionary[key];'  
    get { return whatever; } 
 
    // and here 'value' is whatever you pass to the setter e.g. 'dictionary[kex] = x;' 
    set { whatever = value; } 
} 

在你的情况下会是:

// "Key" is just an example, use "X-RateLimit-requests-Remaining" instead ;) 
response.Headers["Key"];