开发者

Is there a way to get a Type from the namespace/type strings alone?

开发者 https://www.devze.com 2023-01-19 07:58 出处:网络
I am needing to reference a type in an external assembly.I know the namespace and the type name and I know the assembly will be in the GAC, but that\'s it.Is there a way to get this type.I see there\'

I am needing to reference a type in an external assembly. I know the namespace and the type name and I know the assembly will be in the GAC, but that's it. Is there a way to get this type. I see there's a way to get it from a GUID or Pro开发者_如何转开发gram ID which works for me, but I know the people who develop the external assembly may drift away from these COM-like attributes. So, I don't want to depend on them.

Just for a frame of reference, I'd like my software to be very versatile when it comes to this external software being upgraded. So I can't depend on certain versions of assemblies being there for me.


You can load an assembly by name if its in the GAC and then iterate though all its types using Assembly.GetTypes(). You can use loadpartialname but its deprecated to get an assembly with out the fully qualified name.

Look at Assembly.Load()
and Assembly.GetType()


Do you know the assemblyname or do you not know?
if you know the assembylname than it is easy:

Object Creator(string assemblyname, string classname) 
{
   System.Type objType = System.Type.GetType(assemblyname + "." + classname);
   Return Activator.CreateInstance(objType);
}


Since you know this is guaranteed to be in the GAC, you could list the results of gacutil /l. This will give you a list of every assembly in the GAC.

From that, you could start a loop that did the following:

foreach assemblyName in list
    Create new AppDomain
    Load assembly into new appdomain
    check for type in assembly
    if exists:
        return assemblyName to main appDomain
    Unload appdomain

It's important to do this in a separate AppDomain, or you'll load all of these assemblies permanently into your program.

Note that this is going to be very, very slow, and not exactly something I'd recommend. Once you know the proper type name, you should most likely cache this in your app settings for future loads.


Edit:

As Hans points out, Gacutil requires a .NET SDK installation to use. If this is not a valid option, you can use C++/CLI to make a .NET accessable API to retrieve information from the GAC. There is a Native API for accessing GAC information, but this is not a managed API.

0

精彩评论

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

关注公众号