简体   繁体   English

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

[英]Can I use attributes to restrict usage of interface methods in C#?

What I'd like to do is create a custom attribute called [AdminOnly] that applies to fields and methods. 我想要做的是创建一个名为[AdminOnly]的自定义属性,该属性适用于字段和方法。 I'd like it to restrict which methods you can call of an object, depending on how that object was instantiated. 我希望它限制你可以调用一个对象的方法,具体取决于该对象的实例化方式。 So if you instantiate the object with this [AdminOnly] attribute, then you should be allowed to call any methods also tagged with this [AdminOnly] attribute. 因此,如果使用此[AdminOnly]属性实例化对象,则应允许您调用也使用此[AdminOnly]属性标记的任何方法。 But if you don't instantiate the object with that attribute, then you should not have access to those methods. 但是,如果您没有使用该属性实例化对象,那么您不应该有权访问这些方法。

Here's some pseudo-code to illustrate the outcome of what I'm trying to achieve: 这里有一些伪代码来说明我想要实现的结果:

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();
        }
    }
}

First of all, is this (or something like this) possible with attributes in C#? 首先,C#中的属性是否可以(或类似的东西)? If so, how might I go about this? 如果是这样,我怎么能这样做呢? Thanks! 谢谢!

Most attributes only work in runtime, only a few predefined attributes participate in compiling. 大多数属性仅在运行时工作,只有少数预定义属性参与编译。

As I know (correct me if i'm wrong), it's not possible to change the behavior of compiler as you intend to by creating a custom attribute 据我所知(如果我错了,请纠正我),不可能通过创建自定义属性来改变编译器的行为

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM