c# - 带有 DescriptionAttribute 的 .NET Standard 可移植库错误

标签 c# attributes .net-core compatibility .net-standard

我创建了一个 .NET Standard 库,其中包含将在 .NET Framework 应用程序和 .NET Core 应用程序之间共享的模型。

我有一个使用 DescriptionAttributeenum。这是 .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.'

enter image description here

我尝试添加 System.ComponentModel.Primitives,但仍然有错误。

编辑

这是我的项目结构:

enter image description here

最佳答案

要获得加载 .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/

相关文章:

c# - 我可以在业务层使用 TransactionScope 而不是在数据提供程序中使用 SQLiteTransaction 吗?

c#-4.0 - AllowHtml 属性在生产中不起作用

macos - 在 Cocoa 中设置符号链接(symbolic link)的修改日期

c# - 如何配置 asp.net kestrel 以实现低延迟?

c# - 创建和处置 SecretClient

c# - 如何使用 C# 在 asp.net 中的循环中获取 texbox 的值?

c# - 与 SMSS 相比,从 ADO.NET 执行具有相同查询计划的相同查询需要大约 10 倍的时间

C# 查询 - 非静态方法需要目标

javascript - 在纯 JavaScript 中自动计算数据属性的总和

.net - 找不到指定的框架 'Microsoft.AspNetCore.App',版本 '2.2.5'