I have a class MyClass
that need to be serialized, one property will get a list of classes that implement ICamera
and create one instance of the class selected in the propertygrid
Is it possible for me to serialize the class with the selected instance. I want it to be done dynamically without the MyClass
has any idea about the classes implements ICamera
Here is an example of my code so far
[XmlRoot("MyClass")]
public class MyClass
{
private List<string> GetClassesImplementICameraList()
{
List<string> classObject = new List<string>();
var classesWithProperties =
Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => t.GetInterfaces().Contains(typeof(ICamera)) && t.IsClass)
.Select(c => new { ClassName = c.FullName})
.ToList();
foreach (var field in classesWithProperties)
{
classObject.Add(field.ClassName);
}
return classObject;
}
[Browsable(false)]
public List<string> CameraClassesList
{
get { return GetClassesImplementICameraList(); }
}
private ICamera _Camera = null;
[Category("Camera")]
[Description("The camera physically connected to the frame grabber.")]
public ICamera Camera
{
get { return _Camera as ICamera; }
}
private string _CameraMode = string.Empty;
[TypeConverter(typeof(CameraModeTypeConverter))]
[XmlIgnore]
[Category("Camera")]
public string CameraMode
{
get
{
return _CameraMode;
}
set
{
_CameraMode = value;
_Camera = GetCameraInstance(_CameraMode);
}
}
private ICamera GetCameraInstance(string name)
{
ICamera cameraInstance = null;
var instances = from t in Assembly.GetExecutingAssembly().GetTypes()
where t.GetInterfaces().Contains(typeof(ICamera))
&& t.GetConstructor(Type.EmptyTypes) != null && t.FullName == name
select Activator.CreateInstance(t) as ICamera;
foreach (var instance in instances)
{
cameraInstance = instance;
}
return cameraInstance;
}
}