Friday, December 21, 2012

Sử dụng builtin attribute và tạo attribute mới trong C#

[sourcecode language="csharp"]
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Reflection;

namespace ACS_Lab01
{
class Program
{
DateTime date = DateTime.Now;

/// <summary>
/// Tach ham tu thu vien he thong
/// </summary>
/// <param name="c"></param>
/// <param name="text">Noi dung hien thi</param>
/// <param name="caption">Tieu de hop thoai</param>
/// <param name="type">Kieu hop thoai</param>
/// <returns></returns>
[DllImport("User32.dll")]
public static extern int MessageBox(int c, string text, string caption, int type);

static void Main(string[] args)
{
Program objPro = new Program();
objPro.add(3, 5);

Console.WriteLine("*****************************************");
// doc thong tin cac phuong thuc cua lop program
MethodInfo[] methods = typeof(Program).GetMethods();
object[] attributes = null;
for (int i = 0, l = methods.GetLength(0); i < l; i++)
{
MethodInfo mi = methods[i];
// chi lay ve cac custom attribute
attributes = mi.GetCustomAttributes(true);
foreach (Attribute attribute in attributes)
{
if (attribute is Author)
{
Console.WriteLine("Thong tin lien quan phuong thuc " + mi.Name);
Author author = (Author)attribute;
System.Console.WriteLine("Ten tac gia: {0} ,ghi chu: {1} , tao vao : {2}", author.FullName, author.Comment, author.CreateDate.ToShortDateString());
}
}
}

Console.ReadLine();
}

// [Obsolete("Do not use this method")]
[Conditional("DEBUG")]
public void add(int a, int b)
{
Console.WriteLine("Ket qua: " + (a + b));

MessageBox(0, "Ket qua: " + (a + b), "Thong tin", 0);
}

[Author("Nguyen Van Mit", "Very easy")]
[Author("Tran Thi Chom Chom", "Sai giai thuat")]
public int Add(int a, int b)
{
return a + b;
}
}
}
[/sourcecode]

Author attribute
[sourcecode language="csharp"]
using System;
using System.Collections.Generic;
using System.Text;

namespace ACS_Lab01
{
/// <summary>
///
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple=true)]
class Author: System.Attribute
{
/// <summary>
/// Ham khoi tao su dung de cung cap thong tin cho cac thuoc tinh
/// </summary>
/// He ten tac gia
/// Ngay tao ra
public Author(string FullName, string Comment)
{
this.FullName = FullName;
this.CreateDate = DateTime.Now;
this.Comment = Comment;
}

private string _comment;
/// <summary>
/// Ghi chu
/// </summary>
public string Comment
{
get { return _comment; }
set { _comment = value; }
}


private string _name;
/// <summary>
/// Ho ten tac gia
/// </summary>
public string FullName
{
get { return _name; }
set { _name = value; }
}

private DateTime _create;
/// <summary>
/// Ngay toa ra
/// </summary>
public DateTime CreateDate
{
get { return _create; }
set { _create = value; }
}

}
}
[/sourcecode]

Nếu cần demo ban gửi mail cho tôi

No comments:

Post a Comment

Translate