我创建了一个 .NET Standard
库,其中包含将在 .NET Framework
应用程序和 .NET Core
应用程序之间共享的模型。
我有一个使用 DescriptionAttribute
的 enum
。这是 .NET Standard 1.5
库中的枚举:
using System.ComponentModel;
public enum Foo
{
[Description("Description A")]
A,
[Description("Description B")]
B
}
为了能够使用 DescriptionAttribute
,我在 NuGet 包中添加了 System.ComponentModel.Primitives
。
现在在我的 .NET Framework 应用程序中,我想检索枚举的描述。
.NET Core
和 .NET Framework
获取 enum
描述的实现是不同的。所以在我的 .NET Framework 4.6.2
应用程序中,我有一个扩展 GetDescription
解析 enum
的描述属性并像那样返回它:
public static string GetDescription(this Enum value)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name != null)
{
FieldInfo field = type.GetField(name);
if (field != null)
{
DescriptionAttribute attr =
Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
}
}
return null;
}
我得到了那个错误:
System.IO.FileNotFoundException: 'Could not load file or assembly 'System.ComponentModel.Primitives, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.'
我尝试添加 System.ComponentModel.Primitives
,但仍然有错误。
编辑
这是我的项目结构:
最佳答案
要获得加载 .NET Standard <= 1.6 库所需的完整程序集,您应该安装 NETStandard.Library
NuGet 包以及该库引用的任何其他包(如果您使用的是packages.config
基于 .NET Framework 项目。
在某些情况下,通过在 csproj 文件中添加以下代码段,告诉 msbuild 在构建期间更新构建程序集的 .config
文件以包括绑定(bind)重定向,可以修复类似的错误。当库引用 .NET Standard 项目并且由不包含的托管应用程序加载时,通常需要这样做。 (例如经典的单元测试项目):
<PropertyGroup>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
</PropertyGroup>
然而,在您的情况下(.NET Framework 控制台应用程序引用 .NET Standard 库)如果您安装了所有需要的 NuGet 包,则不需要这样做。您的 app.config
文件应自动包含必要的重定向。
请注意,在 VS 2017 15.3 中,这将发生变化,您不再需要引用 NuGet 包来将必要的兼容性库添加到构建输出中。
关于c# - 带有 DescriptionAttribute 的 .NET Standard 可移植库错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45512580/