繁体   English   中英

如何在C#中使用反射从类型和设置属性值中按名称获取属性

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

我正在学习有关C#反射的知识,并在此过程中遇到了一些障碍。 我有一个示例问题,我尝试执行以下操作:

  1. 创建学生的新实例-我了解Student sT = new Student()
  2. 获取实例类型-据我了解: var getType = sT.GetType();
  3. 从类型中按名称获取属性FullName-如何实现?
  4. 使用反射将属性值设置为“某些名称”。 我该如何实现?
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 "";
    }
}

提前致谢。

你快到了; 现在只需在属性信息上调用SetValue即可:

//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");

您还可以遍历属性

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
            }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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