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

时间:2018-08-09 15:00:04

标签: c#

我正在创建一个最多接受4个参数的属性。

我是这样编码的:

binding

我需要这样使用它:

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

是否可以在上述4个构造函数中的一个构造函数中进行编码以避免重复?

我在考虑类似JavaScript的传播运算符public class ExampleModel : BaseAnnotations { /// <summary> /// Example's Identification /// </summary> [Only(GET, DELETE)] public long? IdExample { get; set; } // ...

谢谢。

4 个答案:

答案 0 :(得分:11)

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

[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)]

答案 1 :(得分:3)

好的答案,尽管考虑改为使用4个属性。对于您的示例,这可能有效。

public class GetAttribute: Attribute {}
public class PostAttribute: Attribute {}
public class PatchAttribute: Attribute {}
public class DeleteAttribute: Attribute {}

[GET] [DELETE]
public long? IdExample { get; set; }

简单直接。当然,还有更多的属性,但是您可能需要的实例更多。

每个属性都有一个默认构造函数。仅存在每个操作的属性就足以传达允许的内容。

答案 2 :(得分:1)

您可以尝试

public OnlyAttribute(params string[] parameters)
{
    foreach(var p in parameters) SetMethod(p);
}

答案 3 :(得分:1)

 public OnlyAttribute(params string[] parameters)
 {
        if (parameters.Length > 4) throw new ArugumentException(nameof(parameters));

        foreach (var param in parameters)
        {
            SetMethod(param);
        }
 }