我有一个功能:
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/