Is it possible to set the value of a property using Reflection?

I know the name of the property in my C # class. Can reflection be used to set the value of this property?

For example, let's say I know that the property name is string propertyName = "first_name"; . And there actaully there is a property called first_name . Can I install it using this line?

+22
reflection c #
Oct 10 2018-11-21T00:
source share
2 answers

Yes, you can use reflection - just select its Type.GetProperty (specifying anchor flags if necessary), then call SetValue accordingly. Example:

 using System; class Person { public string Name { get; set; } } class Test { static void Main(string[] arg) { Person p = new Person(); var property = typeof(Person).GetProperty("Name"); property.SetValue(p, "Jon", null); Console.WriteLine(p.Name); // Jon } } 

If this is not a public property, you need to specify BindingFlags.NonPublic | BindingFlags.Instance BindingFlags.NonPublic | BindingFlags.Instance in a GetProperty call.

+57
Oct 10 '11 at
source share

Below my test snippet is written in C # .net

 using System; using System.Reflection; namespace app { class Tre { public int Field1 = 0; public int Prop1 {get;set;} public void Add() { this.Prop1+=this.Field1; } } class Program { static void Main(string[] args) { Tre o = new Tre(); Console.WriteLine("The type is: {0}", o.GetType()); //app.Tre Type tp = Type.GetType("app.Tre"); object obj = Activator.CreateInstance(tp); FieldInfo fi = tp.GetField("Field1"); fi.SetValue(obj, 2); PropertyInfo pi = tp.GetProperty("Prop1"); pi.SetValue(obj, 4); MethodInfo mi = tp.GetMethod("Add"); mi.Invoke(obj, null); Console.WriteLine("Field1: {0}", fi.GetValue(obj)); // 2 Console.WriteLine("Prop1: {0}", pi.GetValue(obj)); // 4 + 2 = 6 Console.ReadLine(); } } } 
-one
Sep 24 '16 at 7:04
source share



All Articles