编程语言
首页 > 编程语言> > C# 反射,根据字符串替换和类中字段

C# 反射,根据字符串替换和类中字段

作者:互联网

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

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

            System.Reflection.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));
            Console.ReadLine();
        }
    }
    public class FieldTest
    {
        public string name;
        public int age;
    }
}

 

标签:中字段,FieldTest,C#,System,fieldTest,fieldInfo,字符串,using,public
来源: https://www.cnblogs.com/duhaoran/p/14298387.html