我想做的是创建一个名为 [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# 中的属性实现?如果是这样,我该怎么办?谢谢!
最佳答案
大部分属性只在运行时起作用,只有少数预定义属性参与编译。
据我所知(如果我错了请纠正我),不可能通过创建自定义属性来改变编译器的行为
关于c# - 我可以使用属性来限制 C# 中接口(interface)方法的使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28754133/