Call Class Property/Method use String Name

1 篇文章 / 0 new
author
Call Class Property/Method use String Name
► Class
public class TestModel
{
    public TestModel(int id, string c1)
    {
        this.id = id;
        this.c1 = c1;
    }
    public int id { get; set; }
    public string c1 { get; set; }
    public DateTime? c2 { get; set; }
    //
    public int getId() {
        return id;
    }
}
► Call Property
Type thisType = i.GetType();
PropertyInfo info = thisType.GetProperty("id");
//thisType.GetProperty(_PropertyName).SetValue(class1, _pair.Value);
Console.WriteLine("id=" + info.GetValue(i, null));

►Call Method
Type thisType = i.GetType();
MethodInfo theMethod = thisType.GetMethod("getId");
Console.WriteLine("call getId()="+ theMethod.Invoke(i,null));
Free Web Hosting