Reputation: 73
I am having an issue when trying to add an interface to a list of base interfaces when the base interface is of a certain type.
My interfaces are defined as below:
public interface IWorkspace<out TWorkspace> where TWorkspace : IWorkspaceBaseModel { }
public interface IWorkspaceBaseModel : IViewBaseModel { }
public interface ILogCollectionViewModel : IWorkspace<IWorkspaceBaseModel> { }
I use the following code to get all the interfaces:
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
var workspaces = assembly
.GetTypes()
.Where(t => typeof(IWorkspace<IWorkspaceBaseModel>).IsAssignableFrom(t) && t.IsInterface)
.ToList();
if (workspaces.Count > 0)
foreach (var wvm in workspaces)
{
var myInterface = (IWorkspaceBaseModel)Activator.CreateInstance(wvm);
}
}
I am getting the error "Cannot create an instance of an interface." and when I the the following code:
var myInterface = (IWorkspace<IWorkspaceBaseModel>)Activator.CreateInstance(wvm);
What i want to do then is add the interface to a list of base interfaces when the have been created:
var viewList = new List<IWorkspaceBaseModel>();
viewList.Add(myInterface);
Any help on how to fix this or a better way of doing it would be greatly appreciated.
Upvotes: 1
Views: 3775
Reputation: 546
I don't know what exactly your intention was, but you can only create instances of classes (that can implement your interfaces).
It's also not possible to write (if IViewModel is an interface):
var myInstance = new IViewModel();
You can find classes that implement an interface:
var assembly = this.GetType().GetTypeInfo().Assembly;
var classes = assembly.DefinedTypes.Where(type => type.ImplementedInterfaces.Any(i => i == typeof(IPageViewModel)));
If you want to create an instance afterwards, you also have to check for non-abstract classes.
Upvotes: 1