Generic Event Generator and Handler from User Supplied Types?

Posted by JaredBroad on Stack Overflow See other posts from Stack Overflow or by JaredBroad
Published on 2013-10-23T20:48:42Z Indexed on 2013/10/23 21:54 UTC
Read the original article Hit count: 128

Filed under:
|
|
|
|

I'm trying to allow the user to supply custom data and manage the data with custom types. The user's algorithm will get time synchronized events pushed into the event handlers they define.

I'm not sure if this is possible but here's the "proof of concept" code I'd like to build. It doesn't detect T in the for loop: "The type or namespace name 'T' could not be found"

class Program
{
    static void Main(string[] args)
    {
        Algorithm algo = new Algorithm();
        Dictionary<Type, string[]> userDataSources = new Dictionary<Type, string[]>();

        // "User" adding custom type and data source for algorithm to consume
        userDataSources.Add(typeof(Weather), new string[] { "temperature data1", "temperature data2" });

        for (int i = 0; i < 2; i++)
        {
            foreach (Type T in userDataSources.Keys)
            {
                string line = userDataSources[typeof(T)][i]; //Iterate over CSV data..
                var userObj = new T(line);
                algo.OnData < typeof(T) > (userObj);
            }
        }
    }

    //User's algorithm pattern.
    interface IAlgorithm<TData> where TData : class 
    {
        void OnData<TData>(TData data);
    }

    //User's algorithm.
    class Algorithm : IAlgorithm<Weather> {
        //Handle Custom User Data
        public void OnData<Weather>(Weather data) 
        {   
            Console.WriteLine(data.date.ToString());
            Console.ReadKey();
        }
    }

    //Example "user" custom type.
    public class Weather {
        public DateTime date = new DateTime();
        public double temperature = 0;

        public Weather(string line) {
            Console.WriteLine("Initializing weather object with: " + line);
            date = DateTime.Now;
            temperature = -1;
        }
    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about events