2015-04-04 54 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())); 
    } 
}