Execute/Reject function based on customs attribute value in dotnet core C#

纵然是瞬间 提交于 2019-12-12 05:17:05

问题


I'm trying to learn the attributes in C# dotnet core, so I wrote the 2 below classes.

  1. Attribute class:

    using System;
    
    namespace attribute
    {
       // [AttributeUsage(AttributeTargets.Class)]
       [AttributeUsage(AttributeTargets.All)]
       public class MyCustomAttribute : Attribute
       {
           public string SomeProperty { get; set; }
        }
    
    
    //[MyCustom(SomeProperty = "foo bar")]
    public class Foo
    {
        [MyCustom(SomeProperty = "user")]
        internal static void fn()
        {
            Console.WriteLine("hi");
        }
      }
    }
    
  2. Main class:

    using System;
    using System.Reflection;
    
    namespace attribute
    {
        public class Program
        {
            public static int Main(string[] args)
            {
    
                var customAttributes = (MyCustomAttribute[])typeof(Foo).GetTypeInfo().GetCustomAttributes(typeof(MyCustomAttribute), true);
            if (customAttributes.Length > 0)
            {
                var myAttribute = customAttributes[0];
                string value = myAttribute.SomeProperty;
                // TODO: Do something with the value
                Console.WriteLine(value);
                if (value == "bar")
                    Foo.fn();
                else
                    Console.WriteLine("Unauthorized");
            }
            return 0;
        }
      }
    }
    

I need the function Foo.fn() to be executed if the SomeProperty element in the MyCustomAttribute is equal to bar. My code work fine if I applied it into the class level, but not working on the function level

IMPORTANT NOTE I'm very new to this, so any advice or feedback to improve my code, is welcomed. thanks


回答1:


your solution is to find the declared method & in that method find the attribute.

var customAttributes =  (MyCustomAttribute[])((typeof(Foo).GetTypeInfo())
.DeclaredMethods.Where(x => x.Name == "fn")
.FirstOrDefault())
.GetCustomAttributes(typeof(MyCustomAttribute), true);


来源:https://stackoverflow.com/questions/40088610/execute-reject-function-based-on-customs-attribute-value-in-dotnet-core-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!