2016-10-17 1 views
0

C# dotnet core에서 속성을 배우려고하고 있으므로 아래 2 개의 클래스를 작성했습니다.dotnet core의 customs 속성 값을 기반으로 Execute/Reject 기능 C#

  1. 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"); 
        } 
        } 
    } 
    
  2. 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; 
        } 
        } 
    } 
    
  3. MyCustomAttribute에서 SomeProperty 요소 bar 같으면

I는 Foo.fn()가 실행하는 기능이 필요 . 내 코드 잘 작동 내가 class level으로 적용,하지만이 아주 새로운 해요 function level

중요 참고 에 작동하지 않는, 그래서 어떤 조언이나 의견이 내 코드를 개선 할 경우, 환영합니다. 덕분에

답변

0

귀하의 솔루션은 해당 메서드에서 & 선언 된 메서드를 찾을 속성을 찾을 수 있습니다.

var customAttributes = (MyCustomAttribute[])((typeof(Foo).GetTypeInfo()) 
.DeclaredMethods.Where(x => x.Name == "fn") 
.FirstOrDefault()) 
.GetCustomAttributes(typeof(MyCustomAttribute), true); 
+0

감사합니다, 나는 확인하고 확인,하지만 내가 다른 클래스에 많은 기능과 같은 속성을 사용하지 않은 경우, 나는 각 기능에 대한 유사한 문을 다시 작성해야 할, 또는이 있습니다 속성을 확인하는 더 좋은 방법은 그것이 사용되는 케르세틴입니다. –

+0

어떤 클래스에서 어떤 함수를 호출해야 하는지를 알고 있어야합니다. 확장 메서드로 쉽게 만들 수 있습니다 (코어가 지원하기를 바랍니다). –

관련 문제