I m currently working on a VariableWatcher
class in C#.
What I want to do, is to raise a event every time a variable is changed to a specific value.
For example: I have a bool a
, which is false. I pass it to the VariableWatcher class thogether with the value on which the event should be raised, true
.
I already made an approach to the solution of this problem, but I obviously misunderstood some point about boxing/unboxing.
这是我的法典:
public class ValueWatch
{
public delegate void ValueTriggeredD(string ID, string valuename, object source);
public event ValueTriggeredD ValueTriggered;
Dictionary<string, object[]> LookUp = new Dictionary<string, object[]>(); //Key = ID, Value[0] = PropertyName, Value[1] = ObjTrigger, Value[2] = ObjWatch
Timer ttt;
public void Initialize()
{
ttt = new Timer(new TimerCallback(CB_T), null, 0, 50);
}
void CB_T(object o)
{
if (LookUp.Count > 0)
{
foreach (KeyValuePair<string, object[]> kvp in LookUp)
{
Type tp = kvp.Value[2].GetType();
FieldInfo inf = tp.GetField((string)kvp.Value[0]);
if (inf != null)
{
object curval = inf.GetValue(kvp.Value[2]);
if (curval == kvp.Value[1])
{
if (ValueTriggered != null)
ValueTriggered(kvp.Key, (string)kvp.Value[0], kvp.Value[2]);
}
}
}
}
}
public void StartWatching(string ID, object ListObj, object ValueForTrigger, string PropertyName)
{
if (LookUp.ContainsKey(ID))
System.Diagnostics.Debug.Print("already there");
else
{
LookUp.Add(ID, new object[] { PropertyName, ValueForTrigger, ListObj });
}
}
public void StopWatching(string ID)
{
LookUp.Remove(ID);
}
}
我的问题是:在我改变价值时,为什么储存在数值中的物体不会改变?
例:
bool b = false;
valueWatch.ValueTriggered += new ValueTriggeredD(this.VT);
valueWatch.StartWatching("ID1", this, true, "b");
...
b = true;
...
void VT(string ID, string VN, object Source)
{
//Never triggered
}