简体   繁体   English

HttpWebRequest集合初始化C#

[英]HttpWebRequest collection Initializer C#

When using HttpWebRequest via HttpWebRequest.Create(url) is there an easier way than the following to initialize a HttpWebRequest by using a object initializer: 通过HttpWebRequest.Create(url)使用HttpWebRequest时,有一种比以下更简单的方法通过使用对象初始化程序来初始化HttpWebRequest:

class RequestLight
{
    public HttpWebRequest WebRequestObj;

    public RequestLight(string url)
    {
        WebRequestObj = HttpWebRequest.CreateHttp(url);
    }

}

Now this can be used like so (desired effect of object initializer for webreq object) 现在可以像这样使用(webreq对象的对象初始化器的预期效果)

var obj = new RequestLight("http://google.com") 
                { WebRequestObj = { CookieContainer = null } }.WebRequestObj;

Am I missing something? 我想念什么吗? Or is this the easiest way to get the desired effect? 还是这是获得理想效果的最简单方法?

Note: Using the original way you have to set create the object via a static method then assign each property one by one. 注意:必须使用原始方法通过静态方法设置创建对象,然后逐个分配每个属性。

It sounds like you're looking for a way to initialize the request in a single statement - otherwise just using two statements is simpler. 听起来您正在寻找一种在单个语句中初始化请求的方法-否则仅使用两个语句会更简单。

There's a reasonably simple alternative to this, using a lambda expression - although it's pretty nasty... 使用lambda表达式有一个相对简单的替代方法-虽然很讨厌...

public static class Extensions
{
    public static T Initialize<T>(this T value, Action<T> initializer) where T : class
    {
        initializer(value);
        return value;
    }
}

And call it with: 并调用:

var request = WebRequest.CreateHttp(uri)
    .Initialize(x => x.CookieContainer = null);

Or for multiple properties: 或针对多个属性:

var request = WebRequest.CreateHttp(uri).Initialize(x => {
    x.CookieContainer = null;
    x.Date = DateTime.UtcNow;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM