我正在编写一个创建 Hammock REstRequest 对象扩展的过程,并且想知道哪种实现(非常相似)会被认为是更好的编程实践。这是对象定义,它有 2 个构造函数
public class RequestObject : RestRequest
{
public RequestObject()
{
this.Encoding = System.Text.Encoding.UTF8;
System.Net.ServicePointManager.Expect100Continue = false;
}
public RequestObject(WebMethod webMethod, byte[] ContentArray)
: this()
{
if (webMethod == Hammock.Web.WebMethod.Put
|| webMethod == Hammock.Web.WebMethod.Post)
{
//encode payload string to a utf8 byte array
this.AddPostContent(ContentArray);
this.AddHeader("Content-Type", "application/json");
}
}
}
对于对象的构造,我有两种方法可以做到,内联实例化它,如下:
string payload = serializer.Serialize(user);
RequestObject request
= new RequestObject(WebMethod.Put, BuildAPI.GetBytes(payload))
{
Credentials = new BasicAuthCredentials
{
Username = ConfigurationManager.AppSettings["UserName"],
Password = ConfigurationManager.AppSettings["Password"]
},
UserAgent = ConfigurationManager.AppSettings["UserAgent"],
};
或者调用“构建类”的成员来构造对象:
public static RequestObject BuildRequest(WebMethod method, byte[] byteArray)
{
RequestObject request = new RequestObject(WebMethod.Put, byteArray)
{
Credentials = new BasicAuthCredentials
{
Username = ConfigurationManager.AppSettings["UserName"],
Password = ConfigurationManager.AppSettings["Password"]
},
UserAgent = ConfigurationManager.AppSettings["UserAgent"],
Method = method
};
return request;
}
并按如下方式调用它:
RequestObject request = BuildAPI.BuildRequest(WebMethod.Put, payload);
我只是想知道这两个选项中的哪一个被认为是更好的编程实践。我正在阅读 SOLID,现在我对同一类中的多个“功能”感到紧张,但不想过度思考。