反射值类型的Interlocked.Increment
我想使用 Interlocked.Increment 来增加对象的整数成员,但我想通过反射引用这些整数。我的示例代码无法正常工作,如下所示。
public class StatBoard
{
#region States (count of)
public int Active;
public int Contacting;
public int Polling;
public int Connected;
public int Waiting;
public int Idle;
#endregion
protected IEnumerable<FieldInfo> states;
public StatBoard()
{
Type foo = GetType();
FieldInfo[] fields = foo.GetFields(BindingFlags.Instance & BindingFlags.Public);
states = from n in fields
where n.FieldType == typeof(int)
select n;
}
public void UpdateState(string key)
{
FieldInfo statusType = states.First(
i => i.Name == key
);
System.Threading.Interlocked.Increment(ref (int)statusType.GetValue(this));
}
}
如何修改 UpdateState 方法才能使其正常工作?
I want to increment integer members of an object using Interlocked.Increment, but I want to reference those integers via reflection. Example code I have, which is not working, is below.
public class StatBoard
{
#region States (count of)
public int Active;
public int Contacting;
public int Polling;
public int Connected;
public int Waiting;
public int Idle;
#endregion
protected IEnumerable<FieldInfo> states;
public StatBoard()
{
Type foo = GetType();
FieldInfo[] fields = foo.GetFields(BindingFlags.Instance & BindingFlags.Public);
states = from n in fields
where n.FieldType == typeof(int)
select n;
}
public void UpdateState(string key)
{
FieldInfo statusType = states.First(
i => i.Name == key
);
System.Threading.Interlocked.Increment(ref (int)statusType.GetValue(this));
}
}
How do I modify the UpdateState method to make this work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这在设计上是行不通的。 int 是一种值类型。 GetValue() 方法返回 int 的副本。您将增加该副本,而不是原始副本。反射没有任何方法来获取对值类型值的引用。
This cannot work by design. An int is a value type. The GetValue() method returns a copy of the int. You'll increment that copy, not the original. Reflection doesn't have any way to get a reference to a value type value.