简体   繁体   English

C#中的类型名称空间问题

[英]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. 我有第三方.Net程序集,可以说ThridParty.dll,它使用的是来自.Net程序集dotnetassembly.dll的类型“ dotnet-namespace.dotnet-type”。现在,在dotnetassembly.dll的新版本中,“ dotnet-type”在dotnet-中较早名称空间已移至新的名称空间,可以说new-dotnet-namespace。dotnet-type的全限定名称已成为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? 现在我的问题是,有什么办法可以告诉运行时在新名称空间(即new-dotnet-namespace)而不是旧名称空间(即dotnet-namespace)中寻找dotnet-type类型?

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. 我没有选择使用从新命名空间使用类型的thridparty.dll的新版本的选项。

No, there is nothing in .Net Framework to redirect one type to another. 不,.Net Framework中没有任何东西可以将一种类型重定向到另一种类型。

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". 请注意,名称空间只是使源代码中的名称更短的语法糖,因为.Net本身名称空间只是类型名称的一部分-因此,您的问题本质上是“我可以将类型指向另一个类型”。

Solutions: 解决方案:

  • recompile 重新编译
  • build proxy assembly 建立代理程序集
  • rewrite IL to point to new types. 重写IL以指向新类型。

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. 您可以将SingleOrDefault更改为FirstOrDefault并使其返回第一次出现。

Of course you'd lose all the compiler-time advantages, since you'll be looking up the type at runtime. 当然,您将失去所有编译时优势,因为您将在运行时查找类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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