Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am not sure if this is possible but I want to iterate through a class and set a field member property without referring to the field object explicitly:

public class Employee
{
  public Person _person = new Person();

  public void DynamicallySetPersonProperty()
  {
    MemberInfo[] members = this.GetType().GetMembers();

    foreach (MemberInfo member in members.Where(a => a.Name == "_person"))
    //get the _person field
    {

      Type type = member.GetType();
      PropertyInfo prop = type.GetProperty("Name"); //good, this works, now to set a value for it

      //this line does not work - the error is "property set method not found"
      prop.SetValue(member, "new name", null);
    }
  }
}


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

In the answer that I marked as the answer you need to add:

  public static bool IsNullOrEmpty(this string source)
  {
    return (source == null || source.Length > 0) ? true : false;
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
647 views
Welcome To Ask or Share your Answers For Others

1 Answer

Here's a complete working example:

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

class Program
{
    static void PropertySet(object p, string propName, object value)
    {
        Type t = p.GetType();
        PropertyInfo info = t.GetProperty(propName);
        if (info == null)
            return;
        if (!info.CanWrite)
            return;
        info.SetValue(p, value, null);
    }

    static void PropertySetLooping(object p, string propName, object value)
    {
        Type t = p.GetType();
        foreach (PropertyInfo info in t.GetProperties())
        {
            if (info.Name == propName && info.CanWrite)
            {
                info.SetValue(p, value, null);
            }
        }
    }

    static void Main(string[] args)
    {
        Person p = new Person();

        PropertySet(p, "Name", "Michael Ellis");
        Console.WriteLine(p.Name);
        PropertySetLooping(p, "Name", "Nigel Mellish");
        Console.WriteLine(p.Name);
    }
}

EDIT: added a looping variant so you could see how to loop through property info objects.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...