此代码是在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;
}
}