如何创建一个具有可选参数和参数的方法?
static void Main(string[] args)
{
TestOptional("A",C: "D", "E");//this will not build
TestOptional("A",C: "D"); //this does work , but i can only set 1 param
Console.ReadLine();
}
public static void TestOptional(string A, int B = 0, params string[] C)
{
Console.WriteLine(A);
Console.WriteLine(B);
Console.WriteLine(C.Count());
}
Run Code Online (Sandbox Code Playgroud) 我最近阅读了以下溢出帖子: C#的隐藏功能
其中一个特征是arglist.为什么选择这个或替代方法作为对方法使用可变长度参数列表的方法?另外,请注意我可能不会在我的代码中使用这种构造,除非有必要这样做.这更像是一个语义问题,而不是甚至使用可变长度参数是否实际或谨慎.那么有谁知道哪个更好,为什么?
[Test]
public void CanHandleVariableLengthArgs()
{
TakeVariableLengthArgs(__arglist(new StringBuilder(), 12));
object[] arr = { new StringBuilder() };
TakeVariableLengthArgs2(arr);
TakeVariableLengthArgs3(
new Dictionary<string, object>
{ { "key", new StringBuilder() } });
}
public void TakeVariableLengthArgs(__arglist)
{
var args = new ArgIterator(__arglist);
var a = (StringBuilder)TypedReference.ToObject(args.GetNextArg());
a.Append(1);
}
public void TakeVariableLengthArgs2(params object[] args)
{
var a = (StringBuilder)args[0];
a.Append(1);
}
public void TakeVariableLengthArgs3(Dictionary<string, object> args)
{
var a = (StringBuilder)args["StringBuilder"];
a.Append(1);
}
Run Code Online (Sandbox Code Playgroud) 我正在创建一个最多接受4个参数的属性.
我用这种方式编码:
internal class BaseAnnotations
{
public const string GET = "GET";
public const string POST = "POST";
public const string PATCH = "PATCH";
public const string DELETE = "DELETE";
public class OnlyAttribute : Attribute
{
public bool _GET = false;
public bool _POST = false;
public bool _PATCH = false;
public bool _DELETE = false;
public OnlyAttribute(string arg1)
{
SetMethod(arg1);
}
public OnlyAttribute(string arg1, string arg2)
{
SetMethod(arg1);
SetMethod(arg2);
}
public OnlyAttribute(string arg1, string arg2, string arg3)
{
SetMethod(arg1); …Run Code Online (Sandbox Code Playgroud)