views:

203

answers:

1

Hi, I want to do my component that works similar to most of data controls (MS, Telerek, etc.):

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

I have some test code:

 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>());
  }
 }

Of course I want to get rid of c.bind(data.Cast<object>());. What type should I pass as argument to that function? I have tried to pass Object, but there is a problem with casting argument back into list(control should be very universal and I dont want to have any fixed data types). Thanks in advance.

A: 

You can try a generic method:

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

One easy performance hint: consider caching the PropertyInfo instance instead of re-generating it in each call to process().

Justin Grant