Nền tảng Kiến thức - Hành trang tới Tương lai
Card image

Chương trình học


  1. Cài đặt môi trường Lập trình C# 2
    1. Cài đặt Visual Studio
    2. Môi trường phát triển .NET
  2. Nhập môn Lập trình C# 18
    1. Giới thiệu ngôn ngữ lập trình C#
    2. Cấu trúc chương trình C#
    3. Cú pháp cơ bản C#
    4. Các kiểu dữ liệu trong C#
    5. Chuyển đổi kiểu dữ liệu trong C#
    6. Khởi tạo biến trong C#
    7. Hằng số trong C#
    8. Toán tử trong C#
    9. Điều kiện trong C#
    10. Vòng lặp trong C#
    11. Tính bao đóng trong C#
    12. Tạo phương thức/hàm trong C#
    13. Đối tượng Nullable trong C#
    14. Mảng trong C#
    15. Chuỗi trong C#
    16. Cấu trúc trong C#
    17. Enums trong C#
    18. Truyền Tham số Reference hay Tham trị (Value) trong C#
  3. Hướng đối tượng trong C# 11
    1. Class trong C#
    2. Kế thừa trong C#
    3. Tính đa hình trong C#
    4. Nạp chồng toán tử trong C#
    5. Giao diện (Interface) trong C#
    6. Namespace trong C#
    7. Các lệnh tiền xử lý trong C#
    8. Biểu thức chính quy (Regular) trong C#
    9. Bắt các lỗi/ngoại lệ (Exception) trong C#
    10. Xử lý Đọc/Ghi File trong C#
    11. LINQ trong C#
  4. Các kỹ thuật nâng cao trong C# 2
    1. Thuộc tính (Attributes) trong C#
    2. Biên dịch ngược (Reflection) trong C#
  5. Bài tập thực hành 27
    1. Khai báo các Kiểu dữ liệu cho Mẫu Lý lịch A2 và Mẫu Hóa đơn Bán hàng
    2. Sử dụng các Toán tử cơ bản trong C#
    3. Kiểm tra số chẵn hay lẻ
    4. Thay đổi vị trí của 2 phần tử
    5. Tính tổng các kí tự số
    6. Đảo ngược con số
    7. Tạo chương trình ATM đơn giản
    8. Tạo chương trình ATM đơn giản với các phương án rút tiền theo các mệnh giá
    9. Tìm số Max, Min trong mảng 2 chiều
    10. Tạo cấu trúc lưu trữ thông tin Nhân viên
    11. Làm quen Hướng đối tượng trong C#
    12. Mã hóa chuỗi với Hacker Speak (H4ck3rSp34k)
    13. Mã hóa chuỗi với Alternating Captions (AlTeRnAtInG_CaPs​​​​​)
    14. Tính tổng 2 số nhỏ nhất trong danh sách
    15. Trích xuất thông tin từ dữ liệu trong FILE TEXT
    16. In bảng cửu chương
    17. In tam giác Nhị phân
    18. In tam giác Số ký tự
    19. Đếm số 1
    20. Sử dụng Mảng 2 chiều để in tên dạng Asterisk ra màn hình
    21. Sử dụng Mảng 1 chiều để phân tách Tên với khoảng cách
    22. Bài tập Biểu thức Chính quy (Regular Expression)
    23. Ghi log lỗi với File và Try Catch
    24. Ghi Access log
    25. LINQ group by tên tập tin
    26. LINQ với collection
    27. Tạo chương trình Quản lý Danh sách Sinh viên và Giảng viên
  6. Kiểm tra kiến thức 1
    1. Kiểm tra kiến thức Lập trình C#
  7. Kiểm tra kiến thức - Đồ án 2
    1. Bài tập Kiểm tra Thực hành C# - Đề 01
    2. Bài tập Kiểm tra Thực hành C# - Đề 02

Chương 4-Bài 1. Thuộc tính (Attributes) trong C#

Tác giả: Dương Nguyễn Phú Cường
Ngày đăng: Hồi xưa đó

An attribute is a declarative tag that is used to convey information to runtime about the behaviors of various elements like classes, methods, structures, enumerators, assemblies etc. in your program. You can add declarative information to a program by using an attribute. A declarative tag is depicted by square ([ ]) brackets placed above the element it is used for. Attributes are used for adding metadata, such as compiler instruction and other information such as comments, description, methods and classes to a program. The .Net Framework provides two types of attributes: the pre-defined attributes and custom built attributes.

Specifying an Attribute

Syntax for specifying an attribute is as follows −
[attribute(positional_parameters, name_parameter = value, ...)]
element
Name of the attribute and its values are specified within the square brackets, before the element to which the attribute is applied. Positional parameters specify the essential information and the name parameters specify the optional information.

Predefined Attributes

The .Net Framework provides three pre-defined attributes −
  • AttributeUsage
  • Conditional
  • Obsolete

AttributeUsage

The pre-defined attribute AttributeUsage describes how a custom attribute class can be used. It specifies the types of items to which the attribute can be applied. Syntax for specifying this attribute is as follows −
[AttributeUsage (
   validon,
   AllowMultiple = allowmultiple,
   Inherited = inherited
)]
Where,
  • The parameter validon specifies the language elements on which the attribute can be placed. It is a combination of the value of an enumerator AttributeTargets. The default value is AttributeTargets.All.
  • The parameter allowmultiple (optional) provides value for the AllowMultiple property of this attribute, a Boolean value. If this is true, the attribute is multiuse. The default is false (single-use).
  • The parameter inherited (optional) provides value for the Inheritedproperty of this attribute, a Boolean value. If it is true, the attribute is inherited by derived classes. The default value is false (not inherited).
For example,
[AttributeUsage(
   AttributeTargets.Class |
   AttributeTargets.Constructor |
   AttributeTargets.Field |
   AttributeTargets.Method |
   AttributeTargets.Property, 
   AllowMultiple = true)]

Conditional

This predefined attribute marks a conditional method whose execution depends on a specified preprocessing identifier. It causes conditional compilation of method calls, depending on the specified value such as Debug or Trace. For example, it displays the values of the variables while debugging a code. Syntax for specifying this attribute is as follows −
[Conditional(
   conditionalSymbol
)]
For example,
[Conditional("DEBUG")]
The following example demonstrates the attribute −
#define DEBUG
using System;
using System.Diagnostics;

public class Myclass {
   [Conditional("DEBUG")]
   
   public static void Message(string msg) {
      Console.WriteLine(msg);
   }
}
class Test {
   static void function1() {
      Myclass.Message("In Function 1.");
      function2();
   }
   static void function2() {
      Myclass.Message("In Function 2.");
   }
   public static void Main() {
      Myclass.Message("In Main function.");
      function1();
      Console.ReadKey();
   }
}
When the above code is compiled and executed, it produces the following result −
In Main function
In Function 1
In Function 2

Obsolete

This predefined attribute marks a program entity that should not be used. It enables you to inform the compiler to discard a particular target element. For example, when a new method is being used in a class and if you still want to retain the old method in the class, you may mark it as obsolete by displaying a message the new method should be used, instead of the old method. Syntax for specifying this attribute is as follows −
[Obsolete (
   message
)]

[Obsolete (
   message,
   iserror
)]
Where,
  • The parameter message, is a string describing the reason why the item is obsolete and what to use instead.
  • The parameter iserror, is a Boolean value. If its value is true, the compiler should treat the use of the item as an error. Default value is false (compiler generates a warning).
The following program demonstrates this −
using System;

public class MyClass {
   [Obsolete("Don't use OldMethod, use NewMethod instead", true)]
   
   static void OldMethod() {
      Console.WriteLine("It is the old method");
   }
   static void NewMethod() {
      Console.WriteLine("It is the new method"); 
   }
   public static void Main() {
      OldMethod();
   }
}
When you try to compile the program, the compiler gives an error message stating −
Don't use OldMethod, use NewMethod instead

Creating Custom Attributes

The .Net Framework allows creation of custom attributes that can be used to store declarative information and can be retrieved at run-time. This information can be related to any target element depending upon the design criteria and application need. Creating and using custom attributes involve four steps −
  • Declaring a custom attribute
  • Constructing the custom attribute
  • Apply the custom attribute on a target program element
  • Accessing Attributes Through Reflection
The Last step involves writing a simple program to read through the metadata to find various notations. Metadata is data about data or information used for describing other data. This program should use reflections for accessing attributes at runtime. This we will discuss in the next chapter.

Declaring a Custom Attribute

A new custom attribute should is derived from the System.Attribute class. For example,
//a custom attribute BugFix to be assigned to a class and its members
[AttributeUsage(
   AttributeTargets.Class |
   AttributeTargets.Constructor |
   AttributeTargets.Field |
   AttributeTargets.Method |
   AttributeTargets.Property,
   AllowMultiple = true)]

public class DeBugInfo : System.Attribute
In the preceding code, we have declared a custom attribute named DeBugInfo.

Constructing the Custom Attribute

Let us construct a custom attribute named DeBugInfo, which stores the information obtained by debugging any program. Let it store the following information −
  • The code number for the bug
  • Name of the developer who identified the bug
  • Date of last review of the code
  • A string message for storing the developer's remarks
The DeBugInfo class has three private properties for storing the first three information and a public property for storing the message. Hence the bug number, developer's name, and date of review are the positional parameters of the DeBugInfo class and the message is an optional or named parameter. Each attribute must have at least one constructor. The positional parameters should be passed through the constructor. The following code shows the DeBugInfo class −
//a custom attribute BugFix to be assigned to a class and its members
[AttributeUsage(
   AttributeTargets.Class |
   AttributeTargets.Constructor |
   AttributeTargets.Field |
   AttributeTargets.Method |
   AttributeTargets.Property,
   AllowMultiple = true)]

public class DeBugInfo : System.Attribute {
   private int bugNo;
   private string developer;
   private string lastReview;
   public string message;
   
   public DeBugInfo(int bg, string dev, string d) {
      this.bugNo = bg;
      this.developer = dev;
      this.lastReview = d;
   }
   public int BugNo {
      get {
         return bugNo;
      }
   }
   public string Developer {
      get {
         return developer;
      }
   }
   public string LastReview {
      get {
         return lastReview;
      }
   }
   public string Message {
      get {
         return message;
      }
      set {
         message = value;
      }
   }
}

Applying the Custom Attribute

The attribute is applied by placing it immediately before its target −
[DeBugInfo(45, "Zara Ali", "12/8/2012", Message = "Return type mismatch")]
[DeBugInfo(49, "Nuha Ali", "10/10/2012", Message = "Unused variable")]
class Rectangle {
   //member variables
   protected double length;
   protected double width;
   public Rectangle(double l, double w) {
      length = l;
      width = w;
   }
   [DeBugInfo(55, "Zara Ali", "19/10/2012", Message = "Return type mismatch")]
   
   public double GetArea() {
      return length * width;
   }
   [DeBugInfo(56, "Zara Ali", "19/10/2012")]
   
   public void Display() {
      Console.WriteLine("Length: {0}", length);
      Console.WriteLine("Width: {0}", width);
      Console.WriteLine("Area: {0}", GetArea());
   }
}
In the next chapter, we retrieve attribute information using a Reflection class object.

Các bài học

Chương trình học

Bao gồm Module, Chương, Bài học, Bài tập, Kiểm tra...

Chương trình học


  1. Cài đặt môi trường Lập trình C# 2
    1. Cài đặt Visual Studio
    2. Môi trường phát triển .NET
  2. Nhập môn Lập trình C# 18
    1. Giới thiệu ngôn ngữ lập trình C#
    2. Cấu trúc chương trình C#
    3. Cú pháp cơ bản C#
    4. Các kiểu dữ liệu trong C#
    5. Chuyển đổi kiểu dữ liệu trong C#
    6. Khởi tạo biến trong C#
    7. Hằng số trong C#
    8. Toán tử trong C#
    9. Điều kiện trong C#
    10. Vòng lặp trong C#
    11. Tính bao đóng trong C#
    12. Tạo phương thức/hàm trong C#
    13. Đối tượng Nullable trong C#
    14. Mảng trong C#
    15. Chuỗi trong C#
    16. Cấu trúc trong C#
    17. Enums trong C#
    18. Truyền Tham số Reference hay Tham trị (Value) trong C#
  3. Hướng đối tượng trong C# 11
    1. Class trong C#
    2. Kế thừa trong C#
    3. Tính đa hình trong C#
    4. Nạp chồng toán tử trong C#
    5. Giao diện (Interface) trong C#
    6. Namespace trong C#
    7. Các lệnh tiền xử lý trong C#
    8. Biểu thức chính quy (Regular) trong C#
    9. Bắt các lỗi/ngoại lệ (Exception) trong C#
    10. Xử lý Đọc/Ghi File trong C#
    11. LINQ trong C#
  4. Các kỹ thuật nâng cao trong C# 2
    1. Thuộc tính (Attributes) trong C#
    2. Biên dịch ngược (Reflection) trong C#
  5. Bài tập thực hành 27
    1. Khai báo các Kiểu dữ liệu cho Mẫu Lý lịch A2 và Mẫu Hóa đơn Bán hàng
    2. Sử dụng các Toán tử cơ bản trong C#
    3. Kiểm tra số chẵn hay lẻ
    4. Thay đổi vị trí của 2 phần tử
    5. Tính tổng các kí tự số
    6. Đảo ngược con số
    7. Tạo chương trình ATM đơn giản
    8. Tạo chương trình ATM đơn giản với các phương án rút tiền theo các mệnh giá
    9. Tìm số Max, Min trong mảng 2 chiều
    10. Tạo cấu trúc lưu trữ thông tin Nhân viên
    11. Làm quen Hướng đối tượng trong C#
    12. Mã hóa chuỗi với Hacker Speak (H4ck3rSp34k)
    13. Mã hóa chuỗi với Alternating Captions (AlTeRnAtInG_CaPs​​​​​)
    14. Tính tổng 2 số nhỏ nhất trong danh sách
    15. Trích xuất thông tin từ dữ liệu trong FILE TEXT
    16. In bảng cửu chương
    17. In tam giác Nhị phân
    18. In tam giác Số ký tự
    19. Đếm số 1
    20. Sử dụng Mảng 2 chiều để in tên dạng Asterisk ra màn hình
    21. Sử dụng Mảng 1 chiều để phân tách Tên với khoảng cách
    22. Bài tập Biểu thức Chính quy (Regular Expression)
    23. Ghi log lỗi với File và Try Catch
    24. Ghi Access log
    25. LINQ group by tên tập tin
    26. LINQ với collection
    27. Tạo chương trình Quản lý Danh sách Sinh viên và Giảng viên
  6. Kiểm tra kiến thức 1
    1. Kiểm tra kiến thức Lập trình C#
  7. Kiểm tra kiến thức - Đồ án 2
    1. Bài tập Kiểm tra Thực hành C# - Đề 01
    2. Bài tập Kiểm tra Thực hành C# - Đề 02

Bài học trước Bài học tiếp theo