指定命名空间的程序集

Fre*_*lad 10 c# wpf xaml namespaces .net-assembly

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

举例来说,如果你同时引用PresentationFramework.Aero,并PresentationFramework.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 ../>
Run Code Online (Sandbox Code Playgroud)

但在C#代码后面我找不到反正创建的实例ButtonChromePresentationFramework.Aero.

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

using Microsoft.Windows.Themes;
// ...
ButtonChrome buttonChrome = new ButtonChrome();
Run Code Online (Sandbox Code Playgroud)

错误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选择哪个,因为我没有告诉它.我能以某种方式这样做吗?

Ken*_*art 8

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

extern alias thealias;
Run Code Online (Sandbox Code Playgroud)

请参阅参考的属性窗口.

假设您将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();
Run Code Online (Sandbox Code Playgroud)

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


Ala*_*lan 5

救援的外部别名,请参阅此处的文档.添加了程序集引用并在相应的引用属性中创建了别名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);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)