c# - 我可以使用属性来限制 C# 中接口(interface)方法的使用吗?

标签 c# annotations attributes

我想做的是创建一个名为 [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/

相关文章:

c# - 在多对多 Entity Framework 关系中保留外键列表

c# - 数百万条记录的数组性能

python - Pyplot注释: roman numerals

java - Eclipse Luna 不保留注释处理生成的代码

python - 在给定特定索引的情况下,如何访问对象列表中的对象属性?

C# ASP.NET、Azure 混合 SQL 连接无法连接到 Web 表单应用程序上的数据库

c# - 如何获取用户文档目录的位置?

spring - 获取 Spring SpEL 表达式上的 java 注释属性值

.net - SignalR Autofac 注入(inject)授权属性

JavaScript:使用或不使用 jQuery 更改 onclick 的值