自动实现的属性是否支持属性?

suh*_*air 6 c# attributes automatic-properties

我被告知在自动实现的属性中不允许使用c#属性.真的吗?如果是这样的话?

编辑:我从一本关于LINQ的流行书中得到了这些信息,并且无法相信!编辑:参考Paul Kimmel释放的LINQ第34页,他说" 在自动实现的属性上不允许属性,所以如果你需要属性,请自行滚动 "

aku*_*aku 12

您可以毫无问题地将属性应用于自动属性.

MSDN引用:

允许在自动实现的属性上使用属性,但显然不在支持字段上,因为无法从源代码访问这些属性.如果必须在属性的支持字段上使用属性,只需创建常规属性.


Jon*_*eet 8

证明错误的最简单方法就是测试它:

using System;
using System.ComponentModel;
using System.Reflection;

class Test
{
    [Description("Auto-implemented property")]
    public static string Foo { get; set; }  

    static void Main(string[] args)
    {
        var property = typeof(Test).GetProperty("Foo");
        var attributes = property.GetCustomAttributes
                (typeof(DescriptionAttribute), false);

        foreach (DescriptionAttribute description in attributes)
        {
            Console.WriteLine(description.Description);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我建议你给作者发电子邮件,以便将其作为一个错误发布.如果他意味着你不能将属性应用于该领域,这将使他有机会更仔细地解释.