首页 文章

指定命名空间的程序集

提问于
浏览
10

无论如何在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 的实例 .

编译时,以下代码为我提供了 error 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 因为我没有告诉它 . 我能以某种方式这样做吗?

3 回答

  • 0

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

    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 alias .

  • 5

    救援的外部别名,请参阅文档here . 添加了程序集引用并在相应的引用属性中创建了别名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);
        }
      }
    }
    
  • 8

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

    在Visual Studio中,转到项目的引用,选择一个生成冲突的程序集,转到属性并使用不等于 global 的值填充别名值 .

相关问题