【问题标题】:.NET Standard portable library error with DescriptionAttribute.NET Standard 可移植库错误与 DescriptionAttribute
【发布时间】:2017-08-04 17:35:58
【问题描述】:

我创建了一个.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 应用程序中,我想检索枚举的描述。

获取enum 描述的实现在.NET Core.NET Framework 之间是不同的。所以在我的.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:'无法加载文件或程序集'System.ComponentModel.Primitives,Version=4.1.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a'或其依赖项之一。系统找不到指定的文件。'

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

编辑

这是我的项目结构:

【问题讨论】:

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


    【解决方案1】:

    要获得加载 .NET Standard packages.config 的 .NET Framework,您应该安装 NETStandard.Library NuGet 包以及该库引用的任何其他包项目。

    在某些情况下,可以通过在 csproj 文件中添加以下 sn-p 来告诉 msbuild 在构建期间更新构建程序集的 .configfile 以包含绑定重定向来修复类似的错误。当库引用 .NET Standard 项目并且由不这样做的托管应用程序加载时,通常需要这样做。 (例如经典的单元测试项目):

    <PropertyGroup>
      <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
      <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
    </PropertyGroup>
    

    但是,在您的情况下(.NET Framework 控制台应用程序引用 .NET Standard 库),如果您安装了所有需要的 NuGet 包,则不需要这样做。您的 app.config 文件应自动包含必要的重定向。

    请注意,在 VS 2017 15.3 中,这将发生变化,您不再需要引用 NuGet 包来将必要的兼容性库添加到构建输出中。

    【讨论】:

    • 顺便说一句,我编辑了我的问题。通过在两个.NET Framework 应用程序中添加NETStandard.Library,我现在得到了这个错误:System.IO.FileLoadException: 'Could not load file or assembly 'System.Runtime, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.
    • 是否也安装了System.Runtime?当我刚刚尝试它时,它被安装为NETStandard.Library 的依赖项,并向App.config 文件添加了绑定重定向,并在构建输出中添加了一个dll。
    • 它不在我的控制台应用程序中。但是,当我添加 NETStandard.Library 时,它会自动添加到 .NET Framework 应用程序中
    • 当我尝试通过 Nuget 管理器添加它时,它说它已经安装,但我在参考中没有看到它...
    • :( 尝试卸载,然后重新安装。有时重新打开 VS 会有所帮助。请注意,在下一次 VS 2017 更新中,将自动添加所需的库。只是用 VS 2017 累了15.3 预览版 7.0,它在 .NET Framework 控制台应用程序中工作,无需添加任何 NuGet 包。
    猜你喜欢
    • 2018-12-31
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多