c#中基于自定义属性值的执行/拒绝函数
本文关键字:执行 拒绝 函数 自定义属性 | 更新日期: 2023-09-27 18:13:20
我正在尝试学习c# dotnet core中的属性,因此我编写了以下2个类。
-
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"); } } }
-
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
上工作
重要提示我对这方面非常陌生,所以欢迎任何建议或反馈来改进我的代码。由于
你的解决方案是找到声明的方法&在该方法中找到属性。
var customAttributes = (MyCustomAttribute[])((typeof(Foo).GetTypeInfo())
.DeclaredMethods.Where(x => x.Name == "fn")
.FirstOrDefault())
.GetCustomAttributes(typeof(MyCustomAttribute), true);