2009-12-20 42 views
53

Tôi muốn biết liệu tôi có thể xác định các thuộc tính lắp ráp tùy chỉnh hay không. thuộc tính hiện tại được định nghĩa theo cách sau:Thuộc tính hội họp tùy chỉnh

[assembly: AssemblyTitle("MyApplication")] 
[assembly: AssemblyDescription("This application is a sample application.")] 
[assembly: AssemblyCopyright("Copyright © MyCompany 2009")] 

Có cách nào tôi có thể làm như sau:

[assembly: MyCustomAssemblyAttribute("Hello World! This is a custom attribute.")] 

Trả lời

77

Có bạn có thể. Chúng tôi làm điều này.

[AttributeUsage(AttributeTargets.Assembly)] 
public class MyCustomAttribute : Attribute { 
    string someText; 
    public MyCustomAttribute() : this(string.Empty) {} 
    public MyCustomAttribute(string txt) { someText = txt; } 
    ... 
} 

Để đọc, hãy sử dụng loại linq stmt này.

var attributes = assembly 
    .GetCustomAttributes(typeof(MyCustomAttribute), false) 
    .Cast<MyCustomAttribute>(); 
8

Có, sử dụng AttributeTargets.Assembly:

[AttributeUsage(AttributeTargets.Assembly)] 
public class AssemblyAttribute : Attribute { ... } 
Các vấn đề liên quan