c# - 函数中参数的可变顺序

标签 c# variables parameters optional-parameters

我有一个功能:

public static bool Substr(string source, out string output, string begining, int length = -1, string end = null)
{
    output = "";
    int start_;
    if ((start_ = source.IndexOf(begining, StringComparison.Ordinal)) != -1)
    {
        start_ += begining.Length;
        if (length != -1)
        {
            if (start_ +length <= source.Length)
            {
                output = source.Substring(start_, length);
                return true;
            }
        }else{
            int end_;
            if ((end_ = source.IndexOf(end, start_, StringComparison.Ordinal)) != -1)
            {
                output = source.Substring(start_, end_ -start_);
                return true;
            }
        }
    }
    return false;
}

我目前使用的:

string in = "aaaaaaa(bbbbbb)";
string result = Substr(in, out result, "(", -1, ")");

子字符串的结尾是“)”,但我必须写-1,我不使用它,因为第四个参数预计是 int

或者像这样:

string in = "aaaaaaa(bbbbbb)";
string result = Substr(in, out result, "(", 6);

子字符串的结尾是“(”之后的第 6 个字符

如何使第四个参数为整数或字符串,以便我可以将其用作:

string result = Substr(in, out result, "(", ")");

我的灵感来自 C# native 函数,例如 infexOf:

string i = "aaaaa(bbbb)";
int x = i.IndexOf("(", 3, StringComparison.Ordinal);
int y = i.IndexOf("(", StringComparison.Ordinal);

在本例中,第二个参数是 int 或 StringComparison。

如何让编译器根据参数数据类型来决定,而不是期望参数的确切顺序? 请注意,我不是在寻找“命名和可选参数”https://msdn.microsoft.com/en-us/library/dd264739(v=vs.100).aspx

最佳答案

How do I make compiler decide by parameter data type instead of expecting exact order of parameters?

你不知道。这是不可能的,在很多情况下甚至行不通。

Note that I am not looking for "Named and Optional Arguments"

如果您出于某种原因必须避免命名参数(请注意,无论如何您已经在使用可选参数),请继续使用多个重载:

public static bool Substr(string source, out string output, string begining, int length, string end)
public static bool Substr(string source, out string output, string begining, string end)
public static bool Substr(string source, out string output, string begining, int length)
public static bool Substr(string source, out string output, string begining)

每个具有较少参数的重载都只是调用具有最多参数的一个实现。

关于c# - 函数中参数的可变顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37629409/

相关文章:

java - 调用过程默认值而不将值绑定(bind)到 Jdbc 中的参数

function - PowerShell 传递函数中接收到的所有参数,并处理带空格的参数

c# - 从 URL 读取响应的最简单方法

c# - 如何识别一个字符串是否包含多个特定字符的实例?

php - 这些 PHP 条件是否相同或有优势

javascript - 关于 JavaScript 变量作用域的问题

groovy - 如何在 Jenkins Workflow 中编辑构建参数?

c# - 创建仅比较日期并截断时间的查询

c# - 这行在 Python 中是什么意思?

php - 将一个巨大的 html 文件转换为 php 变量/echo