12

无论如何在 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# 代码中,我无论如何都找不到创建ButtonChromein的实例PresentationFramework.Aero

以下代码在编译时给了我错误 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选择哪个,因为我没有告诉它。我能以某种方式做到这一点吗?

4

3 回答 3

10

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

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();

有关详细信息,请参阅外部别名

于 2012-06-08T21:39:30.030 回答
6

救援的外部别名,请参阅此处的文档。添加了程序集引用并在各自的引用属性中创建了别名 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);
    }
  }
}
于 2012-06-08T21:49:54.720 回答
1

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

在 Visual Studio 中,转到项目的引用,选择产生冲突的程序集之一,转到属性并用不等于global的值填充 Aliases 值。

于 2015-07-06T11:36:57.333 回答