我正在创建一个最多接受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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我需要像这样使用它:
public class ExampleModel : BaseAnnotations
{
/// <summary>
/// Example's Identification
/// </summary>
[Only(GET, DELETE)]
public long? IdExample { get; set; }
// ...
Run Code Online (Sandbox Code Playgroud)
有没有办法只在一个构造函数中编码上面的4个构造函数以避免重复?
我正在思考JavaScript的扩展运算符(...args) => args.forEach(arg => setMethod(arg)).
提前致谢.
Mar*_*ell 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;
}
Run Code Online (Sandbox Code Playgroud)
然后呼叫者可以使用:
[Only(AllowedVerbs.Get)]
Run Code Online (Sandbox Code Playgroud)
要么
[Only(AllowedVerbs.Post | AllowedVerbs.Delete)]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
151 次 |
| 最近记录: |