簡體   English   中英

有沒有一種方法可以直接從getter或setter訪問屬性的屬性?

[英]Is there a way to directly access the attributes of a property from the getter or setter?

我有一個看起來像這樣的屬性:

<DataElement(0, 4)>
Private Property RiffId As String
   Get
      Dim mb As MethodBase = MethodBase.GetCurrentMethod()
      Dim de As DataElementAttribute = mb.GetCustomAttribute(Of DataElementAttribute)()
      ...
  End Get
  Set(value As String)
     ...
  End Set
End Property

(此項目是VB,但完全歡迎使用C#答案。)

變量de包含null / Nothing,因為該屬性適用於整個屬性,而不適用於mb變量包含的getter。 是否有一種方便直接的方法來獲取“父”方法庫,而無需獲取getter的名稱,剝離開頭的“ get_”並搜索類的屬性以獲取該屬性的屬性? 我看不到,但也許我忽略了它。

好吧,沒有絕對的直接方法,但是您可以為其尋找相當安全的方法(不涉及任何字符串)。 看一下這個例子:

using System;
using System.Linq;
using System.Reflection;

public class Program
{
    [ObsoleteAttribute("foo")]
    public static string MyProp
    {
        get
        {
            var mb = MethodBase.GetCurrentMethod();
            var prop = mb.DeclaringType.GetProperties().Single(x => x.GetGetMethod() == mb);
            return prop.GetCustomAttribute<ObsoleteAttribute>().Message;
        }
    }

    public static void Main()
    {
        Console.WriteLine(MyProp);
    }
}

結果是:

FOO

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM