Hi i write a some plugins
it's look like that
public class Person
{
public string Name;
public string Surname;
}
public interface IWork
{
Type GetType {get;}
}
public interface IWorker<T> : IWork
{
T GetSingle();
T[] GetMultiple();
void DoWork(T object);
}
one plugin looks like that
public PersonPlugin : IWroker<Person>
{
//implementation of interface
//return typeof(Person);
}
And now question, how i can dynamic create a instance for example of IWork ? How cast as IWork if i have only Type, it's possible ?
i want to do (should be dynamic, for all instance of plugins)
IWork<T> iWorkInstalce = (IWork<T>)Activator.CreateInstance(typeof(PersonPlugin));
or
IWork iWorkInstalce = (IWork)Activator.CreateInstance(typeof(PersonPlugin)开发者_StackOverflow社区);
IWork<Person> personInstance = (CAST) typeof(IWork<>).MakeGenericType(iWorkInstance.Type);
You can't cast to IWorker<T>
without specifying what T
is. If you do that, your first example is valid:
IWorker<Person> iWorkInstalce = (IWorker<Person>)Activator.CreateInstance(typeof(PersonPlugin));
It is possible to use reflection on the PersonPlugin
class to find it's implementation of IWorker<T>
, and then discover what T
is, but this is only any use as runtime, it won't help you at all in code.
If you know what you expect T
to be, specify it explicitly. Otherwise, cast to the non-generic IWork
instead and give it versions of your methods that return Object
. If you don't know what T
is at compile-time, having a generic IWorker<T>
can't really help you here.
If your application needs to know what type your plugin works with at runtime, it can call the GetType
property.
精彩评论