zoukankan      html  css  js  c++  java
  • C# 反射,根据字符串替换和类中字段或属性

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

    上代码:

    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; }
        }
    }
  • 相关阅读:
    media query不一致
    数据库设计三范式
    异步概念及使用场景
    关于webservice框架CXF的总结
    通过bash文件(shell命令)对文件进行修改
    shell命令相关问题
    shell对文本进行操作命令
    虚拟机安装系统常见问题
    安装autotools系列工具
    Centos和Ubuntu下打包项目
  • 原文地址:https://www.cnblogs.com/duhaoran/p/14298387.html
Copyright © 2011-2022 走看看