【问题标题】:Creating my own component with DataSource and DataBind()使用 DataSource 和 DataBind() 创建我自己的组件
【发布时间】:2010-12-15 06:35:24
【问题描述】:

我想做与大多数数据控件(MS、Telerek 等)类似的组件:

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&lt;object&gt;());。我应该将什么类型作为参数传递给该函数?我试图传递对象,但是将参数转换回列表存在问题(控件应该非常通用,我不想有任何固定的数据类型)。 提前致谢。

【问题讨论】:

    标签: c# .net list user-controls data-binding


    【解决方案1】:

    你可以试试通用方法:

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

    一个简单的性能提示:考虑缓存PropertyInfo 实例,而不是在每次调用process() 时重新生成它。

    【讨论】:

      猜你喜欢
      • 2017-04-20
      • 2020-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多