gpt4 book ai didi

c# - 如何创建最多接受 4 个参数的构造函数?

转载 作者:太空狗 更新时间:2023-10-29 22:10:21 25 4
gpt4 key购买 nike

我正在创建一个最多接受 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);
SetMethod(arg2);
SetMethod(arg3);
}

public OnlyAttribute(string arg1, string arg2, string arg3, string arg4)
{
SetMethod(arg1);
SetMethod(arg2);
SetMethod(arg3);
SetMethod(arg4);
}

public void SetMethod(string arg)
{
switch (arg)
{
case GET: _GET = true; break;
case POST: _POST = true; break;
case PATCH: _PATCH = true; break;
case DELETE: _DELETE = true; break;
}
}
}
}

我需要像这样使用它:

public class ExampleModel : BaseAnnotations
{
/// <summary>
/// Example's Identification
/// </summary>
[Only(GET, DELETE)]
public long? IdExample { get; set; }

// ...

有什么方法可以只在一个构造函数中编写上述 4 个构造函数以避免重复?

我正在考虑类似 JavaScript 的扩展运算符 (...args) => args.forEach(arg => setMethod(arg))

提前致谢。

最佳答案

我建议重新考虑您的设计。考虑:

[Flags]
public enum AllowedVerbs
{
None = 0,
Get = 1,
Post = 2,
Patch = 4,
Delete = 8
}
public class OnlyAttribute : Attribute
{
private readonly AllowedVerbs _verbs;
public bool Get => (_verbs & AllowedVerbs.Get) != 0;
public bool Post => (_verbs & AllowedVerbs.Post) != 0;
public bool Patch => (_verbs & AllowedVerbs.Patch) != 0;
public bool Delete => (_verbs & AllowedVerbs.Delete ) != 0;
public OnlyAttribute(AllowedVerbs verbs) => _verbs = verbs;
}

然后调用者可以使用:

[Only(AllowedVerbs.Get)]

[Only(AllowedVerbs.Post | AllowedVerbs.Delete)]

关于c# - 如何创建最多接受 4 个参数的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51770310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com