views:

157

answers:

2

My question stems from MVC's SelectList (and previous generations). Basically the class takes in an IEnumerable and uses the members you define as strings.

  1. How does it interface with the object (casting, reflection?)
  2. (probably redundant) How does it lookup the members as a string.

This is one facet of C# that I have been interested in but could never find examples of :(


EDIT:

I ended up using DataBinder.Eval() from System.Web.UI

It still has the overhead of reflection but makes things easier by allowing you to pass the object and a string containing the hierarchy of the member you want. Right now that doesn't really mean much, but this project was designed to take in Linq data, so not having to worry about it down the road makes my life a tad easier.

Thanks everyone for the help.

+3  A: 

While I don't know about its implementation for sure, I'd expect it to use reflection.

Basically you call Type.GetProperty or Type.GetMethod to get the relevant member, then ask it for the value of that property for a specific instance (or call the method, etc). Alternatively there's Type.GetMembers, Type.GetMember etc.

If you want to be able to use "Person.Mother.Name" or similar "paths" you have to do that parsing yourself though, as far as I'm aware. (There may be bits of the framework to do it for you, but they're not in the reflection API.)

Here's a short but complete example:

using System;
using System.Reflection;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Test    
{
    static void Main()
    {
        Person jon = new Person { Name = "Jon", Age = 33 };
        ShowProperty(jon, "Name");
        ShowProperty(jon, "Age");
    }

    static void ShowProperty(object target, string propertyName)
    {
        // We don't need no stinkin' error handling or validity
        // checking (but you do if you want production code)
        PropertyInfo property = target.GetType().GetProperty(propertyName);
        object value = property.GetValue(target, null);
        Console.WriteLine(value);
    }
}
Jon Skeet
@Downvoter: Care to give a reason? Did I make a mistake? Do you disapprove of the complete lack of error checking etc?
Jon Skeet
This works, but there is also DataBinder.Eval() which takes in an expression (like member.submember[1].value). This is what MultiSelectList / SelectList uses. There seems to be some tie in to the page controls though, so this might have negative side effects... When I finish up this task I will post what I used.
envalid
@envalid: Sounds like a good plan to me :)
Jon Skeet
+1  A: 

Yes, via reflection. Take a look at the Type class and associated methods. A good place to start might be here.

You can always look at MVC's source for examples too.

BioBuckyBall