【问题标题】:How to initialize WebClient using object initializers?如何使用对象初始化器初始化 WebClient?
【发布时间】:2015-12-01 09:02:46
【问题描述】:

我有一个这样的WebClient

WebClient _webClient = new WebClient
{
    UseDefaultCredentials = true,
    Encoding = System.Text.Encoding.UTF8,               
};
_webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

我想使用对象初始化器来初始化Headers

WebClient _webClient = new WebClient
{
    UseDefaultCredentials = true,
    Encoding = System.Text.Encoding.UTF8,
    Headers = new WebHeaderCollection
    {
        "user-agent",
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)",
    }
};

但是我不知道怎么写。有可能吗?

2016/07/07 更新

关于indexerObject and Collection Initializers。在普通集合中,例如 List<int> numbers 您可以通过以下代码进行初始化

    List<int> numers = new List<int> {
        1, 2, 3
    };

但是WebHeaderCollectio我们要初始化的名字头不是List&lt;...&gt;只是WebClient中的一个通用属性

public class WebClient : Component
{
    ...
    public WebHeaderCollection Headers { get; set; }
    ...
}

Object and Collection Initializers 提到集合初始化器允许您在初始化实现 IEnumerable 的集合类或具有 Add 扩展方法的类时指定一个或多个元素初始化器。

所以让我们检查WebHeaderCollection

public class WebHeaderCollection : NameValueCollection, ISerializable
{
    public string this[HttpResponseHeader header] { get; set; }

    public string this[HttpRequestHeader header] { get; set; }

    public void Add(string header);

    public void Add(HttpRequestHeader header, string value);

    public void Add(HttpResponseHeader header, string value);
}

WebHeaderCollection : NameValueCollection : NameObjectCollectionBase : IEnumerable

最后还有一个我的练习示例

 class Program
    {
        static void Main(string[] args)
        {
            PeopleEnumerable peopleEnumerable = new PeopleEnumerable {
                { "Michael", "1" },
                { "Mike", "2" },
                { "Butters;3" },
            };

            Console.WriteLine(peopleEnumerable["1"]);
            Console.WriteLine(peopleEnumerable["2"]);
            Console.WriteLine(peopleEnumerable["3"]);
        }
    }

    public class PeopleEnumerable : IEnumerable
    {
        Dictionary<string, string> _peopels = new Dictionary<string, string>();

        public string this[string id]
        {
            get
            {
                return _peopels[id];
            }
            set
            {
                _peopels[id] = value;
            }
        }

        public void Add(string name, string id)
        {
            _peopels.Add(id, name);
        }
        public void Add(string nameAndId)
        {
            var name = nameAndId.Split(';')[0];
            var id = nameAndId.Split(';')[1];

            _peopels.Add(id, name);
        }

        public IEnumerator GetEnumerator()
        {
            throw new NotImplementedException();
        }
    }

您需要实现 IEnumerable,否则您将得到无法使用集合初始化程序初始化类型“PeopleEnumerable”,因为它没有实现“System.Collections.IEnumerable”

【问题讨论】:

  • 你试过了吗?你有什么异常吗?
  • 是的,我试过了。这是异常消息:{“指定的值没有 ':' 分隔符。\r\n参数名称:标头”}

标签: c# asp.net


【解决方案1】:

你可以这样做。您必须用冒号 (:) 分割属性及其值:

WebClient _webClient = new WebClient
    {
        UseDefaultCredentials = true,
        Encoding = System.Text.Encoding.UTF8,
        Headers = new WebHeaderCollection
        {
            "user-agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"
        }
    };

【讨论】:

  • 谢谢你现在可以工作了,但你能解释一下原因吗?
  • 因为WebHeaderCollection 使用对象初始化器只接受一个变量。您必须像通常在 HTTP 请求中那样拆分它。您实际上尝试创建两个标题。这就是它失败的原因。
  • 那么使用“:”来分割只是WebHeaderCollection定义的?
  • 确实如此。它调用this Add method
【解决方案2】:

我认为您也可以这样做(标题中没有:):

private static WebClient _doClient = new WebClient
{
    BaseAddress = "https://api.digitalocean.com/v2/domains/example.com/",
    Headers = new WebHeaderCollection { { "Authorization", "Bearer " + _digitalOceanApiKey } }
};

【讨论】:

  • 谢谢。这也是工作。但我不知道为什么我会问另一个问题。
  • @MichaelMao WebClient.Headers 有一个 .Add 接受 2 个参数的方法——我基本上使用那个。
  • 您能解释一下为什么可以在构造函数中初始化标头吗?
  • @MichaelMao 它们被称为“对象初始化器”。阅读更多 herehere
  • 我会尝试找出原因并与您分享:D
猜你喜欢
  • 2013-06-27
  • 1970-01-01
  • 1970-01-01
  • 2013-02-24
  • 1970-01-01
  • 2020-02-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多