C#中通过反射修改 结构体和类的字段值 备忘

此代码是在winform窗体示例 改变类中的字段网上方法很多 属性改变可以和字段差不多,但是结构体是值类型 修改起来有点些麻烦 下面是方法:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        StructEnum enum1 = new StructEnum();
        ClassName class1 = new ClassName();

        public Form1()
        {
            InitializeComponent();
        }

        private void SetEnumType(ref StructEnum enumType, string fieldName, string value)
        {
            TempClass class1 = new TempClass() { EnumType = enum1 };
            TypedReference tr = TypedReference.MakeTypedReference(class1, class1.GetType().GetFields());
            enumType.GetType().GetField(fieldName).SetValueDirect(tr, value);
            enumType = class1.EnumType;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            a1 = 6;
            MessageBox.Show(cls1.MyProperty.ToString());
            //string str = comboBox1.Text;
            //MessageBox.Show(str);
            //int i1 = 4;
            //Test(ref i1);
            //MessageBox.Show(i1.ToString());

            //方法一
            //SetEnumType(ref enum1, "MyProperty", "1230");

            //方法二
            var objEnum = (object)enum1;
            var fieldsObjInfos = objEnum.GetType().GetField("MyProperty");
            fieldsObjInfos.SetValue(objEnum, "12588");
            enum1 = (StructEnum)objEnum;


            //类的测试
            var fieldInfo = class1.GetType().GetFields();
            foreach (var item in fieldInfo)
            {
                if (item.Name == "MyProperty1")
                {
                    item.SetValue(class1, 123);
                }
            }
        }




        private void Test(ref int input1)
        {
            input1 = 10;
        }

        private int a1 = 5;
        Class1 cls1;
        private void Form1_Load(object sender, EventArgs e)
        {
            cls1 = new Class1(ref a1);
        }
    }

    public class ClassName
    {
        public string MyProperty;
        public int MyProperty1;
    }
    public struct StructEnum
    {
        public string MyProperty;
        public string MyProperty2;
        public int MyProperty3;
    }

    public class TempClass
    {
        public StructEnum EnumType;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

望天hous

你的鼓励是我最大动力~谢谢啦!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值