In my system there is a bunch of Module classes that all derive from the ModuleBase class. Each of these modules are composed of strongly typed parameters as the following example shows:
public class TestModule : ModuleBase, ITestModule
{
public IParameterArray<bool> param1 { get; set; } = new ParameterArray<bool>();
public IParameterArray<int> param2 { get; set; } = new ParameterArray<int>();
public IParameter<int> param3 { get; set; } = new Parameter<int>();
public TestModule()
{
// Initialize default parameters.
ModuleName = this.GetType().Name;
ModuleInfo = "This is a Test module";
}
}
Now from the outside world I need to access information from these parameters, such as Parameter name, memory location, etc., but I am struggling extracting this information.
Say we had the following instance of TestModule:
var myModule = new TestModule();
And then wanted to extract param1 to be used elsewhere, how could I do that?
Something of the sort:
IParamBase p = myModule.GetParam(string paramName);
Note that both IParameterArray and IParameter derive from IParamBase
So far I came up with 2 ideas, but could not sort either.
-
Create a List that would contain all the Parameters from a module (probably have to get somehow populated at construction of the module), but I would not know how to populate this list and it is probably not a great idea, although having a list would allow me to use Linq and search the parameter of interest rather easily.
-
Using reflection, but here I got the problem of not knowing how to cast a PropertyInfo. Here is what I have tried:
public IParameterBase GetParameter(string paramName) { // Get the Type object corresponding to MyClass. Type myType = typeof(Interfaces.IParameterBase); // Get the PropertyInfo object by passing the property name. PropertyInfo myPropInfo = myType.GetProperty(paramName); return myPropInfo as ParameterBase; }
I also tried this:
public dynamic GetParameter(string paramName)
{
Interfaces.IParameterBase p = new ParameterBase();
foreach (var param in this.GetType().GetProperties())
{
try
{
if (param.Name != paramName)
continue;
else
{
// Circle through all base properties of the selected parameter
foreach (var prop in param.GetType().GetProperties())
{
var value = param.GetPropValue($"{prop.Name}");
p.SetProperty($"MyNameSpace.{param.Name}.{prop.Name}", value);
}
return p;
}
}
catch (Exception e)
{
// Log error...
}
}
return null;
}
Note that I do not want to return a clone as I need to retain some of the references of the properties composing a given parameter. So probably easier to just return a reference of the entire parameter.
Any tips or pointers to help me solving this issue would be very much appreciated :-)
Aucun commentaire:
Enregistrer un commentaire