简体   繁体   中英

How can I Get the property by name from type and Set Propert value using reflection in C#

I'm learning about C# reflection and ran into some road blocks along the way. I have an example problem where I'm trying to perform the following:

  1. Create new instance of Student - That I understand Student sT = new Student()
  2. Get instance type - That I understand: var getType = sT.GetType();
  3. Get property FullName by name from type - How can I achieve this??
  4. Set property value to "Some Name" using reflection. How can I achieve this??
using System;
using System.Reflection;

public class Program
{
    public static void Main()
    {
        //1. Create new instance of Stuedent

        Student sT = new Student();

        //2. Get instance type

        var getType = sT.GetType();

        var myStringProperties1 = getType.GetProperty("FullName",
                typeof(string));

        //3. Get property FullName by name from type  ????

        //4.  Set property value to "Some Name" using reflection        

    }
}

public class Student
{
    public string FullName { get; set; }

    public int Class { get; set; }

    public DateTime DateOfBirth { get; set; }

    public string GetCharacteristics()
    {
        return "";
    }
}

Thanks in advance.

You're almost there; now just call SetValue on the property info:

//1. Create new instance of Student
Student student = new Student();

//2. Get instance type
var getType = student.GetType();

//3. Get property FullName by name from type
var fullNameProperty = getType.GetProperty("FullName",
        typeof(string));

//4.  Set property value to "Some Name" using reflection
fullNameProperty.SetValue(student, "Some Name");

you can also iterator through you properties

foreach (var pro in getType.GetProperties()/* get all your properties*/)
            {
               var type = pro.GetType();//Property type

                var propertyName= pro.Name;//Property name

                pro.SetValue(toObject,value);//set Property value
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM