简体   繁体   中英

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. 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. 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#? 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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