2010年5月23日 星期日

ASP.NET 執行時期動態取得執行個體的屬性

在.NET Framework 要動態取得屬性值,除了利用 System.Reflection 的函式庫之外,還可以用 System.Web.DataBinder 所提供的函式來取得屬性值

範例程式碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;

namespace DataBind
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer = new Customer();
            customer.ID = 1;
            customer.Name = "John";

            Console.WriteLine("GetPropertyValue-ID={0}", DataBinder.GetPropertyValue(customer, "ID"));
            Console.WriteLine("GetPropertyValue-Name={0}", DataBinder.GetPropertyValue(customer, "Name"));
            Console.WriteLine("Eval-Name={0}", DataBinder.Eval(customer, "ID"));
        }
    }

    internal class Customer
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
}
執行結果
GetPropertyValue-ID=1
GetPropertyValue-Name=John
Eval-Name=1

沒有留言:

張貼留言