Getting a member through a string in C #?

My question is related to MVC SelectList (and previous generations). Basically, the class accepts IEnumerable and uses the members that you define as strings.

  • How does it interact with an object (casting, reflection?)
  • (possibly redundant). How he views elements as a string.

This is one aspect of C # that interests me, but could never find examples :(


EDIT

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

It still has reflection overhead, but it is simplified, allowing you to pass an object and a string containing the hierarchy of the member you want. Now this does not really mean much, but this project was designed to receive Linq data, so there is no need to worry about it along the way, which makes my life easier.

Thank you all for your help.

+3
source share
2 answers

Although I don’t know exactly about its implementation, I would expect it to use reflection.

Basically you call Type.GetPropertyor Type.GetMethodto get the corresponding member, then ask it about the value of this property for a specific instance (or call a method, etc.). Alternatively there Type.GetMembers, Type.GetMemberetc ..

"Person.Mother.Name" "", , , . ( , API .)

, :

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);
    }
}
+4

, . Type . .

MVC .

+1

Source: https://habr.com/ru/post/1723043/


All Articles