在 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 ../>
但是在后面的 C# 代码中,无论如何我都找不到在 PresentationFramework.Aero
中创建 ButtonChrome
的实例。
下面的代码在编译时给我error CS0433
using Microsoft.Windows.Themes;
// ...
ButtonChrome buttonChrome = new ButtonChrome();
error CS0433: The type 'Microsoft.Windows.Themes.ButtonChrome' exists in both
'c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\Profile\Client\PresentationFramework.Aero.dll'
and
'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 alias了解更多信息。
关于c# - 为命名空间指定程序集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10956326/