lundi 27 mars 2017

How can I create a data structure containing properties whose types are defined at runtime

I am working on a data visualisation tool. It retrieves a bunch of data from a plain text file and then draws various charts and graphs of that data.

So far I have been working with one set of data of which I know the types.

For example if I'm working with a CSV file that looks like this:

id, username, number of messages, message
23123124, @SomeUsername, 5, This 1s a 5tr1ng
89134349, @AnotherUsername, 8, Another string

Then I can store this in an object like this:

public class SomeClass
{
    private string id;
    private string username;
    private int numberOfMessages;
    private string message;
}

Then I just have a List<SomeClass>.

That's great and everything, but it will only work with that particular CSV file. I want to have a data structure that can be flexible, depending on the contents of the CSV file.

The number of properties and the names of those properties is easily discovered by reading the header row in the first line of the text file. What type each piece of data is isn't clear (e.g. an id could be stored as an int or a string), so I'm going to ask the user to tell the application what type to use for each property. I could do this by displaying the name of each property next to a dropdown with options of string, int, bool etc.

But how do I take that user input and create a data structure that contains properties of those types. So if the user goes through a form with 3 drop downs and selects "String", "Integer" and "Boolean", I effectively want an object that looks like this:

public class SomeClass
{
    private string someString;
    private int someInt;
    private bool someBool;
}

What is the best way of achieving this? I have a reasonable understanding of Generics but not sure how to use them in this case. I have heard of Reflection, the Type class and the dynamic keyword but don't really understand them. I have tried using Dictionaries but keep getting stuck. Are any of these options viable? Are they overkill? Am I overthinking this? HELP ME PLEASE! :D

Thank you!





Aucun commentaire:

Enregistrer un commentaire