2015-04-04 57 views
0

這是我第一次寫一個簡單的自定義屬性。首先,我要表明,我做了什麼如何傳遞自定義屬性也是Enum裝飾類的枚舉值?

providers.cs

public enum Providers 
    { 
     Employee, 
     Product 
    }; 

MyCustomAttribute.cs

[AttributeUsage(AttributeTargets.Class) ] 
    public class ServiceProvider : System.Attribute 
    { 
     private Providers provider;   

     public ServiceProvider(Providers provider) 
     { 
      this.provider = provider;    
     } 

     public Providers CustomProvider 
     { 
      get 
      { 
       return provider; 
      } 
     } 
    } 

A.cs

[ServiceProvider(Providers.Employee)] 
    public class A 
    { 
     public void SomeMethod() 
     { 
      Console.WriteLine(Dataclass.GetRecord("Employee")); 
     } 
    } 

B.cs

​​

dataclass.cs

public static class Dataclass 
    { 
     public static string GetRecord(string key) 
     { 
      return InfoDictionary()[key]; 
     } 

     private static Dictionary<string, string> InfoDictionary() 
     { 
      Dictionary<string, string> dictionary = new Dictionary<string, string>(); 
      dictionary.Add("Employee", "This is from Employees"); 
      dictionary.Add("Product", "This is from proucts"); 
      return dictionary; 
     } 
    } 

目前,我硬編碼從個人類即在 「鑰匙」。 A和B

我所尋找的是,如果我裝修我的A類與[ServiceProvider(Providers.Employee)]那麼GetRecord方法應該讓我的員工相關的價值。

對於B類,如果我裝飾[ServiceProvider(Providers.Product)],我應該能夠獲得與產品相關的值。

NB〜我知道,這僅僅是一個簡單的事情,通過傳遞一個枚舉也並轉換爲字符串來實現,但正如我所說,我學習了自定義屬性,所以我想這樣做那樣只。

請讓我知道如果可能或不可以,如果「是」,那我該如何做到這一點?通過反射

+0

您的'Dataclass'不使用屬性或對其他類進行任何操作。目前還不清楚它是如何一起工作的......(如果你有'Dictionary '的值會更有意義......) – 2015-04-04 11:45:30

+0

尊敬的先生,因爲它只是一個例子,我正在使用DataClass。我主要關注的是如何將類級裝飾值傳遞給Dataclass.GetRecord(「員工」)。我的意思是,如果我用[ServiceProvider(Providers.Employee)]裝飾,該方法應該能夠識別Employee服務。類似的,如果我這樣做,[ServiceProvider(Providers.Product)],只有產品服務會被調用。數據類僅僅是一個例子。 – 2015-04-04 11:50:40

+0

但這不是一個有用的例子,因爲它似乎與你正在做的事沒有關係。爲什麼你會傳遞一個字符串?爲什麼不'DataClass.GetRecord(Providers.Employee)'?而且,在類中使用屬​​性的好處在哪裏,而不是直接作爲參數傳遞?我很抱歉,我只是沒有看到這一點... – 2015-04-04 11:52:53

回答

1

您訪問自定義屬性

var type = typeof(A); 
var attributes = type.GetCustomAttributes(typeof(ServiceProvider),inherit:false); 

這會給你所有的服務提供商組成的數組屬性類A.

你舉的例子並沒有真正告訴你如何想申請,但以適應你有什麼你可以有一個擴展方法

public static class ClassExtenstions 
{ 
    public static Providers? GetServiceProvider<T>(this T cls) where T : class 
    { 
     var attribute = typeof(T).GetCustomAttributes(typeof (ServiceProvider), inherit: false).FirstOrDefault() as ServiceProvider; 
     return attribute != null ? attribute.CustomProvider : (Providers?)null; 
    } 
} 

而在你的類,你會用它作爲

[ServiceProvider(Providers.Employee)] 
public class A 
{ 
    public void SomeMethod() 
    { 
     var provider = this.GetServiceProvider(); 
     Console.WriteLine(Dataclass.GetRecord(provider.ToString())); 
    } 
}