做一个参数可选的一个C#的WebMethod的最佳方式
什么是支持传递给一个C#函数的可选数据的最佳方式?
What is the best way of supporting optional data passed to a C# function?
我在.net定义5个参数的Web服务功能:
I have web service function in .Net which defines 5 arguments:
[WebMethod]
public string UploadFile( string wsURL
, byte[] incomingArray
, string FileName
, string RecordTypeName
, MetaData[] metaDataArray)
这个函数的code不是太长(但不是小事其一),并且只有一个在那里我执行此测试功能的地方,如果有任何元数据[]进行处理:
The code of this function is not too long (but not trivial either) and there is only one place in the the function where I perform this test if there is any MetaData[] to be processed:
if (metaDataArray.Length > 0)
{
Update update = BuildMetaData(metaDataArray);
treq2.Items = new Operation[] { sru, cin, update, fetch};
}
else
{
treq2.Items = new Operation[] { sru, cin, fetch};
}
我需要一个快速和肮脏的版本上面只需要4个参数(即无元数据数组作为最后一个参数),所以我克隆整体功能并删除了IF-ELSE块指的元数据。丑陋的我知道。
I needed a quick and dirty version of the above which only takes 4 arguments (i.e. no "Metadata" array as a final argument) so I cloned the whole function and removed the IF-ELSE block refering to metadata. Ugly I know.
[WebMethod]
public string UploadFileBasic( string wsURL
, byte[] incomingArray
, string FileName
, string RecordTypeName)
现在我想更好地做的事情,我期待的意见的最佳方式来支持这一点。我不想负担与创建一个空数组作为第五个参数客户端程序......我想有我的web服务功能,以足够的智慧来处理这个可选数据。谢谢。
Now I want to do things better and I am looking for advice on the best way to support this. I do not want to burden the client program with creating an empty array as a 5th parameter...I want to have my web service functions to be smart enough to handle this optional data. Thanks.
更改支票在需要5参数(注意,你应该检查,如果该值为null反正)的方法。
Change your check in the method that takes 5 arguments to (note, that you should be checking if the value is null anyway).
if (metaDataArray != null && metaDataArray.Length > 0)
{
Update update = BuildMetaData(metaDataArray);
treq2.Items = new Operation[] { sru, cin, update, fetch };
}
else
{
treq2.Items = new Operation[] { sru, cin, fetch};
}
然后,只需你有4参数版本内部调用5参数版本与metaDataArray参数为null。
Then, simply have your 4 argument version call the 5 argument version internally with the metaDataArray argument null.
[WebMethod]
public string UploadFileBasic( string wsURL,
byte[] incomingArray,
string FileName,
string RecordTypeName)
{
return UploadFile( wsUrl, incomingArray, fileName, RecordTypeName, null );
}