首页 > 技术文章 > C# 反射,根据字符串替换和类中字段或属性

duhaoran 2021-01-19 15:53 原文

在我们日常工作中有没有遇到这样一个问题,就是字符串和字段/属性同名,希望通过字符串自己给字段/属性名字替换。要实现此功能可以用反射。

上代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace CSharpStudy
{
    class Program
    {
        static void Main(string[] args)
        {
            FieldTest fieldTest = new FieldTest();

            //替换字段------------
            FieldInfo fieldInfo = fieldTest.GetType().GetField("name");
            fieldInfo.SetValue(fieldTest, "张三");

            fieldInfo = fieldTest.GetType().GetField("age");
            fieldInfo.SetValue(fieldTest, 123);

            Console.WriteLine(string.Format("{0}的年龄有{1}岁了。", fieldTest.name, fieldTest.age));

            //替换属性------------
            PropertyInfo propertyInfo = fieldTest.GetType().GetProperty("Id");
            propertyInfo.SetValue(fieldTest, 1);

            Console.WriteLine(string.Format("{0}的编号是{1}。", fieldTest.name, fieldTest.Id));
            Console.ReadKey();
        }
    }
    public class FieldTest
    {
        public string name;
        public int age;
        private int id;

        public int Id { get => id; set => id = value; }
    }
}

 

推荐阅读