7

私は、c#では自動実装されたプロパティで属性が許可されていないと言われました。本当?もしそうなら、なぜですか?

編集:私はLINQの人気のある本からこの情報を入手しましたが、信じられませんでした!編集:PaulKimmelによって解き放たれたLINQの34ページを参照してください。彼は「自動実装されたプロパティでは属性は許可されていないので、属性が必要な場合は自分でロールしてください」と述べています。

4

5 に答える 5

12

自動プロパティに問題なく属性を適用できます。

MSDNからの引用:

属性は自動実装されたプロパティで許可されますが、ソースコードからアクセスできないため、バッキングフィールドでは許可されません。プロパティのバッキングフィールドで属性を使用する必要がある場合は、通常のプロパティを作成するだけです。

于 2009-01-21T11:24:05.260 に答える
9

それが間違っていることを証明する最も簡単な方法は、ただテストすることです:

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);
        }
    }
}

著者に電子メールを送信して、正誤表として公開できるようにすることをお勧めします。フィールドに属性を適用できないことを彼が意味した場合、これは彼にもっと注意深く説明する機会を与えます.

于 2009-01-21T11:49:58.657 に答える
4

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:

[Serializable]
public class MyClass
{
    [field:NonSerializedAttribute()]
    public int Id
    {
        get;
        private set;
    }
}

This code compiles, but it doesn’t work. You can apply attribute to property itself, but you can't apply it for backing field.

于 2010-01-14T15:57:41.927 に答える
1

また、Automatic プロパティには CompilerGeneratedAttribute も適用されることに注意してください。

于 2009-01-21T11:49:23.743 に答える