Im currently designing a winforms app that needs to be able to output values of various properties in various classes to a serial/udp port.
I was wondering if there is an easy way to iterate over all of the instances of classes in this project at runtime, and then display to the user a select bunch (maybe by using attributes?) and their corresponding string value so they can output any combination of these values.
So, for (a simplified) example, say i have two classes:
public class ClassA
{
public double Price{get;set;}
public int Units{get;set}
//other properties that I don't want visible to the user
}
public class ClassB
{
public string Name{get;set;}
public string Description{get;set;}
//other properties not visible to the user
}
I will have many instances of these classes instantiated at runtime (and they may not necessarily be linked/referenced/related to each other).
e.g.
public ClassA Cars = new ClassA();
public ClassB Models = new ClassB();
public ClassA PCs = new ClassA();
//set properties of these instances
//etc.. more of these
I would like to gather all of these instances and show the corresponding fields to the user:
Cars.Price = "1000";
Cars.Units = "3";
Models.Name = "BMW";
Models.Description = "Luxury Car";
PCs.Price = "3000";
PCs.Units = "20";
Note that the values will be changing at runtime, and this will need to be updated when sending out data.
I was hoping someone could point me in the right direction here.
EDIT
Looks like this may not be viable.
Is there a way I can store a list of objects, where these objects point to my property/field so that i can retrieve its value? Of course assume that these class instances will be created only once, and I could register the class property/field in my output class. Then the output class can iterate over this list, retrieve the value of the object to which it points to, and then send the required data out?
e.g.
class OutputData
{
Dictionary<string,object> OutputDataList = new Dictionary<string,object>();
public void RegisterData(string displayName, ref object dataField)
{
OutputDataList.Add(displayName,dataField);
}
//iterate over OutputDataList and get the value of the property/field it points to
}
If all of these objects exist for the lifetime of the application and you just need to keep track of all of them you could do that in the constructor for each class, something like:
That way you’d only need to modify the classes you want to track and the instances will get tracked in the overall list. For the problem of which fields to track you can either use reflection or you can store something more interesting in all objects, maybe a
Func<List<string>>which returns all the values of interest.The add line would then be:
You can then do: