2

I have here my model:

public class RoleModel
{
    public int ID { get; set; }
    public string RoleName { get; set; }
    public UserRoleModel TrackAndTrace { get; set; }
    public UserRoleModel MailDelivery { get; set; }
    public UserRoleModel MailAccounting { get; set; }
    public UserRoleModel PerformanceMonitoring { get; set; }
    public UserRoleModel AdminSettings { get; set; }
}

I want to get the value of any key of 'RoleModel'

public bool SaveRoleModule(RoleModel role)
{
    PropertyInfo[] properties = typeof(RoleModel).GetProperties();
    foreach (PropertyInfo property in properties)
    {
       if(property.Name != "ID" && property.Name != "RoleName")
       {
          Console.WriteLine(role[property.Name]);//(this doesn't work) I want it dynamic
          Console.WriteLine(role.TrackAndTrace); //not like this
       }
    }
    return true;
}

I used loop to shorten my code.

Kapitan Teemo
  • 2,144
  • 1
  • 11
  • 25
  • If you need to do this in c#, there are are possibility that you are doing something wrong or decision made based on the wrong assumptions. Can you explain why you need to do this? – Fabio Jan 22 '20 at 06:11

2 Answers2

1

You can use this method here: Get property value from string using reflection in C# like this:

public bool SaveRoleModule(RoleModel role)
{
    PropertyInfo[] properties = typeof(RoleModel).GetProperties();
    foreach (PropertyInfo property in properties)
    {
       if(property.Name != "ID" && property.Name != "RoleName")
       {
          var value = GetPropValue(role, property.Name);
          Console.WriteLine(value);//(this doesn't work) I want it dynamic
          Console.WriteLine(role.TrackAndTrace); //not like this
       }
    }
    return true;
}

public static object GetPropValue(object src, string propName)
{
     return src.GetType().GetProperty(propName).GetValue(src, null);
}
Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
0

You could try something like this: public bool SaveRoleModule(RoleModel role) { PropertyInfo[] properties = typeof(RoleModel).GetProperties(); foreach (PropertyInfo property in properties) { if(property.Name != "ID" && property.Name != "RoleName") { Type t = role.GetType(); PropertyInfo p = t.GetProperty(property.Name); UserRoleModel urm = ((UserRoleModel)p.GetValue(role, null)); // do something with urm } } return true; }

Though Fabio is right, this does seem strange and potentially based on faulty reasoning.

Greg Smith
  • 111
  • 1
  • 4