问题
I'm trying to learn the attributes in C# dotnet core, so I wrote the 2 below classes.
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; } } }
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
回答1:
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);
来源:https://stackoverflow.com/questions/40088610/execute-reject-function-based-on-customs-attribute-value-in-dotnet-core-c-sharp