【问题标题】:Execute/Reject function based on customs attribute value in dotnet core C#dotnet core C#中基于海关属性值的执行/拒绝功能
【发布时间】:2016-10-17 14:07:21
【问题描述】:

我正在尝试学习 C# dotnet core 中的属性,所以我编写了以下 2 个类。

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

如果MyCustomAttribute 中的SomeProperty 元素等于bar,我需要执行函数Foo.fn()。 如果我将它应用到class level,我的代码可以正常工作,但不能在function level 上工作

重要提示 我对此很陌生,因此欢迎任何改进我的代码的建议或反馈。谢谢

【问题讨论】:

    标签: c# attributes .net-core custom-attributes


    【解决方案1】:

    您的解决方案是找到声明的方法并在该方法中找到属性。

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

    【讨论】:

    • 谢谢,我会检查并确认你,但如果我不使用不同类中的许多函数的相同属性怎么办,我需要为每个函数重写类似的语句,或者那里是检查其使用的槲皮素属性的更好方法。
    • 你应该知道在哪个类中调用哪个函数。那么它可以很容易地创建成一个扩展方法(我希望核心支持它)。
    猜你喜欢
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-04
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多