[英]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.