2014-06-09 2 views
0

다음 특성 클래스가 있다고 가정 해 보겠습니다.사용자 지정 특성 클래스 내부에서 함수를 호출하는 방법

//Attribute Implementation 
    public abstract class TestAttribute : Attribute 
    { 
     public abstract void UpdateSomething(string s); 
    } 


    public class CustomAttTest : TestAttribute 
    { 
     private State state; 

     public CustomAttTest(State state) 
     { 
      this.state = state; 
     } 

     public override void UpdateSomething(string s) 
     { 
      if (state.Equals(State.First)) 
      { 
       Console.WriteLine("First State!! " + s); 
      } 
     } 
    } 

    public enum State 
    { 
     First, Second, Third 
    } 

속성 클래스 내에서 Updatesomthing 함수를 어떻게 호출 할 수 있습니까? 다음은 속성 구현 예입니다.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace ConsoleApplication3 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var foo = new Ferrari(); 
      //How do i call the UpdateSomething implemented insde the CustomAttTest attribute class? 
     } 
    } 

    public abstract class Vehicle 
    { 
     //Coode 
    } 

    [CustomAttTest(State.First)] 
    public class Ferrari : Vehicle 
    { 
     //Code 
    } 

    //Attribute Implementation 
    public abstract class TestAttribute : Attribute 
    { 
     public abstract void UpdateSomething(string s); 
    } 


    public class CustomAttTest : TestAttribute 
    { 
     private State state; 

     public CustomAttTest(State state) 
     { 
      this.state = state; 
     } 

     public override void UpdateSomething(string s) 
     { 
      if (state.Equals(State.First)) 
      { 
       Console.WriteLine("First State!! " + s); 
      } 
     } 
    } 

    public enum State 
    { 
     First, Second, Third 
    } 


} 
+0

나는이 질문을하기 전에 많은 고글 치기를했다. –

답변

1

당신은 반사를 사용할 필요가 :

foo.GetType().GetCustomAttribute<CustomAttTest>().UpdateSomething(...); 

그러나, 당신은 아마 추상 메서드 또는 속성 대신 속성을 사용해야합니다

public abstract class Vehicle 
    { 
     //Coode 
    } 

    [CustomAttTest(State.First)] 
    public class Ferrari : Vehicle 
    { 
     //Code 
    } 

여기에 전체 코드입니다.

+0

감사합니다! 매력처럼 작동합니다. –

+0

안녕하세요 당신은 자동차 클래스 내에 추상 메소드를 추가하고 페라리에서 오버라이드하는 것이 좋은 습관이라고 생각합니까? –

+0

또한 customerAttTest에서 여러 특성의 특성이있을 때 Updatesomthing() 함수를 실행하는 방법이 있습니까? –

관련 문제