تنفيذ/رفض وظيفة على أساس قيمة السمة الجمركية في دوتنيت الأساسية C#
attributes .net-core (1)
الحل الخاص بك هو العثور على الطريقة المعلنة وفي هذه الطريقة العثور على السمة.
var customAttributes = (MyCustomAttribute[])((typeof(Foo).GetTypeInfo())
.DeclaredMethods.Where(x => x.Name == "fn")
.FirstOrDefault())
.GetCustomAttributes(typeof(MyCustomAttribute), true);
أحاول تعلم السمات في C # دوتنيت الأساسية، لذلك كتبت 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; } } }
أحتاج إلى وظيفة Foo.fn()
ليتم تنفيذها إذا كان عنصر SomeProperty
في SomeProperty
يساوي bar
. بلدي التعليمات البرمجية تعمل بشكل جيد إذا قمت بتطبيقه في class level
، ولكن لا يعمل على function level
ملاحظة هامة أنا جديدة جدا لهذا، لذلك أي نصيحة أو ملاحظات لتحسين بلدي رمز، ورحب. شكر