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; }
        }
    }
  • 相关阅读:
    DebugView使用技巧
    网络抓包--Wireshark
    常用curl命令
    chrome.debugger
    修改php.ini 的timezone
    初识Elasticsearch,bulk 操作的遇到的那些事
    chrome 扩展 调试
    sqlite 时间戳转时间
    centos 升级sqlite3
    php 安装redis
  • 原文地址:https://www.cnblogs.com/duhaoran/p/14298387.html
Copyright © 2011-2022 走看看