2009-11-10 52 views
0

我想要做我的組件,大多數數據控件(MS,Telerek等)的工作原理類似:創建我自己的DataSource和的DataBind()組件

myControl.DataSource = new List<myClass>(); 
mycontrol.NameField = "Name"; 
myControl.ValueField = "Value"; 
myControl.DataBind; 

我有一些測試代碼:

class myClass 
{ 
    public String Name 
    { 
    get { return _name; } 
    } 
    ... 
} 

class control 
{ 
    public void process(object o) 
    { 
    Type type = o.GetType(); 
    System.Reflection.PropertyInfo info = type.GetProperty("Name"); 
    object val = info.GetValue(o,null); 
    System.Console.WriteLine(val.ToString()); 
    } 

    public void bind(IEnumerable<object> list) 
    { 
    foreach (object o in list) 
    { 
    process(o); 
    } 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
    control c = new control(); 
    List<myClass> data = new List<myClass>(); 
    data.Add(new myClass("1 name", "first name", 1.0f)); 
    c.bind(data.Cast<object>()); 
    } 
} 

當然我想擺脫c.bind(data.Cast<object>());。我應該傳遞什麼類型的參數作爲該函數的參數?我試圖傳遞Object,但是將參數轉換回列表存在問題(控件應該非常通用,我不想有任何固定的數據類型)。 在此先感謝。

回答

0

你可以嘗試一個通用的方法:

public void bind<T>(IEnumerable<T> list) 
{ 
    foreach (T item in list) 
    { 
    process(item); 
    } 
} 

一個簡單的性能提示:考慮緩存PropertyInfo實例,而不是重新生成它在每次調用process()