3 回答
TA贡献1828条经验 获得超3个赞
我建议在这里重新考虑您的设计。考虑:
[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)]
TA贡献1155条经验 获得超0个赞
好的答案,但请考虑使用 4 个属性。对于您的示例,这可能有效。
public class GetAttribute: Attribute {}
public class PostAttribute: Attribute {}
public class PatchAttribute: Attribute {}
public class DeleteAttribute: Attribute {}
[GET] [DELETE]
public long? IdExample { get; set; }
它简单而直接。当然还有更多属性,但您可能有更多需要它们的实例。
每个属性都有一个默认构造函数。每个操作的属性仅存在就足以传达允许的内容。
TA贡献1772条经验 获得超8个赞
public OnlyAttribute(params string[] parameters)
{
if (parameters.Length > 4) throw new ArugumentException(nameof(parameters));
foreach (var param in parameters)
{
SetMethod(param);
}
}
- 3 回答
- 0 关注
- 216 浏览
添加回答
举报