C# Reflection Issue
I've got an issue when using reflection.
I have a class ETSetting that contains two objects: A current value and a 'default' value. Whenever the method SetToDefault is called, I want to set the current value to the default value.
Here is my function:
public void SetToDefault() {
foreach (FieldInfo fi in Value.GetType().GetFields(BindingFl开发者_高级运维ags.NonPublic | BindingFlags.Public | BindingFlags.Instance)) {
fi.SetValue(Value, fi.GetValue(defaultVal));
}
}
However, when I call that... All sorts of issues occur. I can't say for sure but it's as if I'm reading parts of the memory that I shouldn't be (for example, when Value and defaultVal are both strings, I get all sorts of bad characters like \t, \n, and chinese characters).
Evidently I'm doing something I shouldn't... But what?
Thanks.
Edit: Here is the ETSetting class in total:
public sealed class ETSetting {
public object Value;
private object defaultVal;
public ETSetting(object defaultVal) {
Value = this.defaultVal = defaultVal;
}
public void SetToDefault() {
foreach (FieldInfo fi in Value.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)) {
fi.SetValue(Value, fi.GetValue(defaultVal));
}
}
}
What you want is a copy of an object that represents the default value. You can use serialization for this, or have your objects support ICloneable
, for example:
public sealed class ETSetting<T> where T : ICloneable {
public T Value;
private T defaultVal;
public ETSetting(T defaultVal) {
this.defaultVal = defaultVal;
SetToDefault();
}
public void SetToDefault() {
Value = (T)defaultVal.Clone();
}
}
精彩评论