【问题标题】:Is there a way to directly access the attributes of a property from the getter or setter?有没有办法从 getter 或 setter 直接访问属性的属性?
【发布时间】:2019-01-10 16:11:45
【问题描述】:

我有一个如下所示的属性:

<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_”,并搜索类的属性以获取属性的属性?我没有看到,但也许我忽略了它。

【问题讨论】:

  • 你能解释一下为什么你需要它来这样工作吗?因为它看起来像是针对其他问题的 hack。
  • 我想访问属性的属性。有这么不寻常吗?
  • Is that so unusual?
  • 这个问题 (stackoverflow.com/questions/3628630/…) 讨论了它。我很好奇。

标签: .net vb.net reflection


【解决方案1】:

好吧,没有绝对直接的方法,但您可以搜索它相当安全(不涉及字符串)。看看这个例子:

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

结果是:

富

【讨论】:

  • 这正是我所忽略的。谢谢。
猜你喜欢
  • 1970-01-01
  • 2012-12-14
  • 1970-01-01
  • 1970-01-01
  • 2011-09-27
  • 2017-06-13
  • 1970-01-01
  • 2010-09-07
  • 2018-07-17
相关资源
最近更新 更多