jeudi 20 juillet 2017

Pointing to a property without reflection or databinding

I want to create a class with a property that "variably" points to some other property in another class.

Imagine a class (called "Limiter") with several integer properties (Limit1, Limit2, etc).

I now want a second class ("LimitWatcher") which can "watch" one of those limits. But I want to be able to set which particular limit it is watching in the constructor. I eventually want several instances of LimitWatcher, each one pointing to a separate Limit. The Limit values themselves may change after the Watchers have been instantiated, but the watcher must always see the current value of the Limit that it is watching. So basically, I want to store a reference to an integer.

I know I can accomplish this using reflection (see example below), but I feel as though there might be a simpler way.

using System;
namespace ConsoleApplication4
{
    public class Limiter 
    {
        public int limit1 { get; set; } = 10;
        public int limit2 { get; set; } = 20;
        public void Update()
        {
            limit1++;
            limit2++;
        }
    }
    public class LimitWatcher
    {
        public LimitWatcher(Limiter lim, string propName)
        {
            myLimiter = lim;
            limitName = propName;
        }
        private Limiter myLimiter { get; }
        public string limitName { get; set; }
        //can I do this without reflection:
        public int FooLimit { get { return (int)typeof(Limiter).GetProperty(limitName).GetValue(myLimiter); } }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Limiter lim = new ConsoleApplication4.Limiter();
            LimitWatcher w1 = new LimitWatcher(lim, nameof(lim.limit1));
            LimitWatcher w2 = new LimitWatcher(lim, nameof(lim.limit2));
            lim.Update();
            Console.WriteLine($"1st watcher sees {w1.FooLimit}");  //11
            Console.WriteLine($"2nd watcher sees {w2.FooLimit}"); //21
            Console.ReadKey();
        }
    }
}





Aucun commentaire:

Enregistrer un commentaire