【发布时间】:2016-10-17 14:07:21
【问题描述】:
我正在尝试学习 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 上工作
重要提示 我对此很陌生,因此欢迎任何改进我的代码的建议或反馈。谢谢
【问题讨论】:
标签: c# attributes .net-core custom-attributes