为什么我不能引用System.ComponentModel.DataAnnotations?

Dav*_*Dev 84 c# wpf data-annotations

我正在尝试在我的WPF项目中使用DataAnnotations来指定字符串的最大长度,具体如下:

using System.ComponentModel.DataAnnotations;
Run Code Online (Sandbox Code Playgroud)

但是,我得到了错误

命名空间'System.ComponentModel'中不存在类型或命名空间名称'DataAnnotations'(您是否缺少程序集引用?)

我已经看到了这个命名空间DataAnnotations 存在的其他示例.我正在使用C#4.我有什么理由不能用这个吗?我该怎么办才能修复它?

Har*_*ari 150

您必须引用定义此命名空间的程序集(默认情况下,Visual Studio模板中不会引用它).打开引用管理器并添加对System.ComponentModel.DataAnnotations程序集的引用(Solution explorer - > Add reference - > Select .Net tab - >从列表中选择System.ComponentModel.DataAnnotations)

  • 奇怪的是,VS无法为我提供正常的"潜在修复".想知道为什么... (8认同)

Joh*_*hnB 32

如果使用.NET Core.NET Standard

用:

管理 NuGet 包..

使用管理 NuGet 包

代替:

添加参考...

不要使用添加引用

  • 从命令行 `dotnet add package System.ComponentModel.Annotations` (5认同)

Cat*_*tto 10

参考System.ComponentModel.DataAnnotations

在一个代码文件中有使用System.ComponentModel.DataAnnotations; 在文件的顶部,如:

using System.ComponentModel.DataAnnotations;
Run Code Online (Sandbox Code Playgroud)

右键单击解决方案资源管理器中的项目,为项目添加.NET引用:

在此输入图像描述

希望这可以帮助!这个问题对我有帮助.


Rod*_*ger 6

如果您没有在引用中添加它(像我一样),则还可以添加NuGet System.ComponentModel.Annotations来获取程序集并解决错误。(将其添加到此处,因为此错误的答案仍位于Google的顶部)