开发者

Interlocked.Increment of Reflected Value Type

开发者 https://www.devze.com 2023-01-07 12:00 出处:网络
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.

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消