为 C# webmethod 设置可选参数的最佳方法 [英] Best way of making an argument optional for a C# webmethod

查看:24
本文介绍了为 C# webmethod 设置可选参数的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

支持传递给 C# 函数的可选数据的最佳方式是什么?

What is the best way of supporting optional data passed to a C# function?

我在 .Net 中有 Web 服务函数,它定义了 5 个参数:

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)

这个函数的代码不是太长(但也不是微不足道的),如果有任何 MetaData[] 需要处理,我在函数中只有一个地方执行这个测试:

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)

现在我想把事情做得更好,我正在寻求有关支持这一点的最佳方式的建议.我不想通过创建一个空数组作为第 5 个参数给客户端程序带来负担……我想让我的 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 参数版本在内部使用 metaDataArray 参数为 null 调用 5 参数版本.

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

这篇关于为 C# webmethod 设置可选参数的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆