How to initialize WebClient using object initializ

2020-04-09 18:36发布

问题:

I have a WebClient like this:

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;)");

I want to initialize the Headers using an object initializer:

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;)",
    }
};

But I don't know how to write that. Is it possible?

Update 2016/07/07

It's about indexer and Object and Collection Initializers. In a normal collection e.g List<int> numbers you can init by following code

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

But WebHeaderCollectio which name header we want to initailze is not List<...> just a generic property in WebClient

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

Object and Collection Initializers mentions Collection initializers let you specify one or more element initializers when you initialize a collection class that implements IEnumerable or a class with an Add extension method.

So let we check the WebHeaderCollection class

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

And finally there is a my practice sample

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

You need to implement IEnumerable or you will get Cannot initialize type 'PeopleEnumerable' with a collection initializer because it does not implement 'System.Collections.IEnumerable'

回答1:

You can do it like this. You have to split the property and its value by a colon (:):

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


回答2:

I think you can also do it like this (without the : in the header):

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


标签: c# asp.net