[英]Can I use attributes to restrict usage of interface methods in C#?
我想要做的是创建一个名为[AdminOnly]
的自定义属性,该属性适用于字段和方法。 我希望它限制你可以调用一个对象的方法,具体取决于该对象的实例化方式。 因此,如果使用此[AdminOnly]
属性实例化对象,则应允许您调用也使用此[AdminOnly]
属性标记的任何方法。 但是,如果您没有使用该属性实例化对象,那么您不应该有权访问这些方法。
这里有一些伪代码来说明我想要实现的结果:
namespace MyProject
{
public interface ICoolThingService
{
int PublicMethod1();
bool PublicMethod2(string input);
void PublicMethod3();
[AdminOnly]
bool AdminMethod();
}
public class CoolThingServiceImpl : ICoolThingService
{
...
}
public class MyAdminThing
{
[AdminOnly]
private readonly ICoolThingService _service = new CoolThingServiceImpl();
public bool AllowedAdminMethod()
{
// this should work because the attribute appears on the class
return _service.AdminMethod();
}
}
public MyOtherThing
{
// note the absence of the attribute here
private readonly ICoolThingService _service = new CoolThingServiceImpl();
public bool NotAllowedAdminMethod()
{
// this should not be allowed because the attribute is absent
return _service.AdminMethod();
}
}
}
首先,C#中的属性是否可以(或类似的东西)? 如果是这样,我怎么能这样做呢? 谢谢!
大多数属性仅在运行时工作,只有少数预定义属性参与编译。
据我所知(如果我错了,请纠正我),不可能通过创建自定义属性来改变编译器的行为
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.