自动实现的属性是否支持属性?
有人告诉我,在 C# 中,自动实现的属性不允许使用属性。 真的吗? 如果是这样为什么?
编辑:我从一本关于 LINQ 的流行书中得到了这些信息,简直不敢相信! 编辑:请参阅 Paul Kimmel 的 LINQ Unleashed 第 34 页,其中他说“自动实现的属性上不允许使用属性,因此如果需要属性,请自行创建属性”
I was told that in c# attributes are not allowed on the auto-implemented properties. Is that true? if so why?
EDIT: I got this information from a popular book on LINQ and could not believe it!
EDIT: Refer page 34 of LINQ Unleashed by Paul Kimmel where he says "Attributes are not allowed on auto-implemented properties, so roll your own if you need an attribute"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以毫无问题地将属性应用于自动属性。
引用自 MSDN:
You can apply attributes to automatic properties without a problem.
Quote from MSDN:
证明这是错误的最简单方法就是测试它:
我建议您向作者发送电子邮件,以便他可以将其作为勘误表发布。 如果他的意思是您不能将属性应用于字段,这将使他有机会更仔细地解释。
The easiest way to prove that's wrong is to just test it:
I suggest you email the author so he can publish it as an erratum. If he meant that you can't apply an attribute to the field, this will give him a chance to explain more carefully.
我认为作者的意思是,您不能将自定义属性应用于私有支持字段。
例如,如果要将自动属性标记为非序列化,则不能这样做:
此代码可以编译,但不起作用。
您可以将属性应用于属性本身,但不能将其应用于支持字段。
I think that author meant, that you can't apply custom attributes to private backing field.
For example, if you want to mark automatic property as non serialized, you can't do this:
This code compiles, but it doesn’t work.
You can apply attribute to property itself, but you can't apply it for backing field.
另请注意,任何“自动”属性也将应用 CompilerGenerateAttribute。
Note also that any Automatic property will have the CompilerGeneratedAttribute applied to it as well.
当前版本的 Visual Studio 和 C# 编译器支持此功能。 我使用启用了 C# 8.0 的 VS 16.4.2 进行了测试。 我不知道它是在哪个版本中启用的,但这是个好消息。
语法:
实际用例; 支持整洁/可往返的合格 XML 序列化,无需混乱的支持字段,但避免运行时异常并解决代码分析错误 CA2235:
如果您正在使用 .NET Core 3、.NET Standard 开发新的“SDK”样式项目之一2.1 或更高版本它将立即工作,因为它们默认为语言版本 8。否则,对于所有“旧版”.NET Framework 和非 SDK 项目,您必须将“LangVersion”设置添加到您的项目 如此处记录至“ 8.0”或“最新”。
The current version of Visual Studio and C# compilers support this. I tested with VS 16.4.2 with C# 8.0 enabled. I don't know exactly which version it was enabled in but it's good news.
Syntax:
Practical use case; support neat/round-trip-able qualified XML serialization without messy backing fields but avoid runtime exceptions and resolve code analysis error CA2235:
If you're working on one of the new "SDK" style projects with .NET Core 3, .NET Standard 2.1 or later it will work immediately as they default to language version 8. Otherwise for all "legacy" .NET Framework and non-SDK projects you'll have to add the "LangVersion" setting to your project as documented here to "8.0" or "latest".