开发者

.NET: Calling GetInterface method of Assembly obj with a generic interface argument

I have the following interface:

public interface PluginInterface<T> where T : MyData
{
    List<T> GetTableData();
}

In a separate assembly, I have a class that implements this interface. In fact, all classes that implement this interface are in separate assemblies. The reason is to architect my app as a plugin host, where plugin can be done in the future as long as they implement the above interface and the assembly DLLs are copied to the appropriate folder.

My app discovers the plugins by first loading the assembly and performs the following:

List<PluginInterface<MyData>> Plugins = new List<PluginInterface<MyData>>();
string FileName = ...;//name of the DLL file that contains classes that implement the interface
Assembly Asm = Assembly.LoadFile(Filename);
foreach (Type AsmType in Asm.GetTypes())
{
    //Type type = AsmType.GetInterface("PluginInterface", true);   //
    Type type = AsmType.GetInterface("PluginInterface<T>", true);
    if (type != null)
    {
       PluginInterface<MyData> Plugin = (PluginInterface<MyData>)Activator.CreateInstance(AsmType);

       Plugins.Add(Plugin);
    }
}

The trouble is because neither line where I am getting the type as by doing Type type = ... seems to work, as both seems to be null. I have th开发者_Python百科e feeling that the generic somehow contributes to the trouble. Do you know why?


It looks like you have to use the mangled interface name when querying for the interface:

Type type = AsmType.GetInterface("PluginInterface`1", true);

From MSDN:

For generic interfaces, the name parameter is the mangled name, ending with a grave accent (`) and the number of type parameters. This is true for both generic interface definitions and constructed generic interfaces. For example, to find IExample<T> or IExample<string>, search for "IExample`1".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜