在dotnet核心C#中基于海关属性值执行/拒绝功能 [英] Execute/Reject function based on customs attribute value in dotnet core C#

查看:107
本文介绍了在dotnet核心C#中基于海关属性值执行/拒绝功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图学习C#dotnet核心中的属性,所以我写了下面的2类。

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


  1. 属性类

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


  • 主类

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


  • 我需要函数 Foo.fn()来执行,如果 SomeProperty 元素在 MyCustomAttribute 等于 bar
    如果我将其应用于类级别,但在功能级别中不起作用,我的代码可以正常工作

    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

    推荐答案

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

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

    这篇关于在dotnet核心C#中基于海关属性值执行/拒绝功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆