强制转换变量以设置新值



我正试图将输出视为"200〃;。我在一个平面文件中有大约400个具有不同设置的变量名,我需要加载配置,但很难转换类型来设置设置。

private double test1 = 100;
private void button1_Click(object sender, EventArgs e) {
double testNewType = (double)test1;
testNewType = 200;
Debug.Print(test1.ToString());
}

如果您想设置字段,可以使用反射:

/*
Get type, you can also use
var type = this.GetType();
*/
var type = typeof(YourClassNameWithFields);
/*
Add BindingFlags.DeclaredOnly 
if you only want to set declared fields in current class (ignoring inheritance)
*/
var fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach(var field in fields){
//targetObject is Object to which you want to set value, can be this
field.SetValue(targetObject, newValue);
}

你也可以使用dynamic类型,就像这样:

dynamic obj = yourObject;
obj.fieldName = value;

您打印的是test1,而不是testNewType

Debug.Print(test1.ToString());

Debug.Print(testNewType.ToString());

如果你试图通过引用传递,我不确定C#是否能用替身做到这一点,当你投它的时候肯定不行。

最新更新