指定命名空间的程序集

本文关键字:程序集 命名空间 | 更新日期: 2023-09-27 18:36:47

无论如何都可以在 C# 中指定程序集和命名空间吗?

例如,如果在项目中同时引用PresentationFramework.AeroPresentationFramework.Luna,您可能会注意到它们在同一命名空间中共享相同的控件,但实现方式不同。

ButtonChrome为例。它存在于命名空间 Microsoft.Windows.Themes 下的两个程序集中。

在 XAML 中,您将程序集与命名空间一起包含在内,因此这里没有问题

xmlns:aeroTheme="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero"
xmlns:lunaTheme="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Luna"
<aeroTheme:ButtonChrome ../>
<lunaTheme:ButtonChrome ../>

但是在 C# 代码中,无论如何我都找不到在 PresentationFramework.Aero 中创建 ButtonChrome 实例。

以下代码在编译时给我错误 CS0433

using Microsoft.Windows.Themes;
// ...
ButtonChrome buttonChrome = new ButtonChrome();

错误 CS0433:类型"Microsoft.Windows.Themes.ButtonChrome"存在于两者
中 'c:''Program Files (x86)''Reference Assemblies''Microsoft''Framework.NETFramework''v4.0''Profile''Client''PresentationFramework.Aero.dll'

'c:''Program Files (x86)''Reference Assemblies''Microsoft''Framework.NETFramework''v4.0''Profile''Client''PresentationFramework.Luna.dll'

这是非常可以理解的,编译器无法知道选择哪个ButtonChrome,因为我没有告诉它。我可以以某种方式做到这一点吗?

指定命名空间的程序集

您需要为程序集引用指定别名,然后通过别名导入:

extern alias thealias;

有关引用,请参阅属性窗口。

假设您将 aero 程序集别名为 "aero",将 luna 程序集别名为 "luna"。然后,您可以在同一文件中使用这两种类型,如下所示:

extern alias aero;
extern alias luna;
using lunatheme=luna::Microsoft.Windows.Themes;
using aerotheme=aero::Microsoft.Windows.Themes;
...
var lunaButtonChrome = new lunatheme.ButtonChrome();
var aeroButtonChrome = new aerotheme.ButtonChrome();

有关详细信息,请参阅 extern 别名。

Extern 别名 要救援,请参阅此处的文档。添加程序集引用并在各自的引用属性中创建别名 Luna 和 Aero 后,您可以尝试以下一些示例代码:

extern alias Aero;
extern alias Luna;
using System.Windows;
namespace WpfApplication1
{
  /// <summary>
  /// Interaction logic for MainWindow.xaml
  /// </summary>
  public partial class MainWindow: Window
  {
    public MainWindow()
    {
      InitializeComponent();
      var chrome1 = new Luna::Microsoft.Windows.Themes.ButtonChrome();
      var chrome2 = new Aero::Microsoft.Windows.Themes.ButtonChrome();
      MessageBox.Show(chrome1.GetType().AssemblyQualifiedName);
      MessageBox.Show(chrome2.GetType().AssemblyQualifiedName);
    }
  }
}

我在引用 Microsoft.Scripting 程序集时遇到了关于 System.NonSerializedAttribute 的类似错误,它也定义了此属性(在 Reference.cs 由服务引用生成的文件中找到冲突)。解决此问题的最简单方法与定义别名非常相似,但没有编译难题:

在 Visual Studio 中,转到项目的引用,选择生成冲突的程序集之一,转到"属性",然后用不等于全局的内容填充"别名"值。