简体   繁体   中英

Type namespace issue in C#

I have third party .Net assembly lets say ThridParty.dll which uses type "dotnet-namespace.dotnet-type from .Net assembly dotnetassembly.dll. Now in new version of dotnetassembly.dll "dotnet-type" which was earlier in dotnet-namespace has been moved to new namespace lets say new-dotnet-namespace. Fully qualified name of dotnet-type has become new-dotnet-namespace.dotnet-type.

Now my question is, Is there any way I can tell runtime to look for type dotnet-type in new namespace ie new-dotnet-namespace instead of old namespace ie dotnet-namespace?

I know we can do use assembly redirection when we want to point new version of assembly but is it possible to redirect types within same assembly but to different namespace? I don't have option to get new version of thridparty.dll which uses type from new namespace.

No, there is nothing in .Net Framework to redirect one type to another.

Note that namespace is just syntactic sugar to makes names shorter in source code, for .Net itself namespace is just part of the type name - so your question is essentially "can I point on type to another".

Solutions:

  • recompile
  • build proxy assembly
  • rewrite IL to point to new types.

How about:

public Type FindType(string typeName, string assemblyName)
{
    Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().SingleOrDefault(a => a.GetName().Name == assemblyName);
    return assembly != null ? assembly.GetTypes().SingleOrDefault(t => t.Name == typeName) : null;
}

You would call this:

Type dotNetType = FindType("dotnet-type", "dotnetassembly");

This way you are independent of the type namespace.

As a side note, if you have two types with the same name in that assembly, this method will simply not work because it won't be able to know which type to return (in fact, it'll throw an exception). You can change SingleOrDefault to FirstOrDefault and make it return the first occurence.

Of course you'd lose all the compiler-time advantages, since you'll be looking up the type at runtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM