There might be situations where you want to loop through the members of an object or you want to create some generic means to access the members of one or more classes, so here is how you can access the members of an object in C# in a generic manner.
- Let your class be :-
Public class Car { public string CarName { get; set; } public int CarID { get; set; } public string Color{ get; set; } public System.DateTime SellingDate { get; set; } public void SetCar_ID(int id) { CarID = id; } public Car CreateCar() { Car car = new Car(); car.SetCar_ID(0); return car; } public Car CreateCar(int id) { Car car = new Car(); car.SetCar_ID(id); return car; } }
- You can access the values of data members of an object of Car class using reflection as shown below:-
Car car_obj = new Car() { CarName = "Jaguar", CarID = 1, Color = "Grey", SellingDate = DateTime.Now }; foreach (var headerColumns in typeof(Car).GetProperties()) { var propValue = car_obj.GetType().GetProperty(headerColumns.Name).GetValue(car_obj, null); }
- Calling a method through reflection :- For calling the CreateCar() method of the car_obj instance (created above) of Car class use the code shown below.
car_obj.GetType().GetMethod("CreateCar", Type.EmptyTypes).Invoke(car_obj, null);
above code will call the "CreateCar" method that has no arguments. For calling second "CreateCar" method i.e. the one with arguments, you can use the below code :-
car_obj.GetType(). GetMethod("CreateCar", new Type[]{ Type.GetType("System.Int32")}). Invoke(car_obj, new object[] { 100 });
- In case there is no Overload of the method you want to call, then you can simply write :-
car_obj.GetType().GetMethod("SetCar_ID").Invoke(car_obj, new object[] { 100 });
No comments:
Post a Comment