【问题标题】:How can I access a method's parameter from an associated attribute?如何从关联属性访问方法的参数?
【发布时间】:2023-03-17 01:15:01
【问题描述】:

给定以下类,我如何从 SampleAttribute 中截取 Class1.SampleMethod 的值? 谢谢

Public Class Class1
    <SampleAttribute()> _
    Public Function SampleMethod(ByVal Value As Integer) As Boolean
        Return True
    End Function
End Class

<AttributeUsage(AttributeTargets.Method)> _
Public Class SampleAttribute
    Inherits System.Attribute

    Private _Value As Integer

    Property Value() As Integer
        Get
            Return _Value
        End Get
        Set(ByVal value As Integer)
            _Value = value
        End Set
    End Property

    Public Sub New()

    End Sub
End Class

编辑:

鉴于 Andrew Hare 的回答,也许我正在尝试使用错误的构造。我有一长串类似的方法,每次调用其中一个时我都需要执行一组操作。我认为为它们每个附加一个属性将是最直接的解决方案。有什么建议吗?

【问题讨论】:

    标签: .net vb.net attributes custom-attributes


    【解决方案1】:

    如果您尝试对横切行为进行建模(不相关的对象需要做类似/相同的事情),那么 AOP 就是您要走的路。我已经使用 PostSharp 取得了很好的效果,无论是编译还是运行时编织。它基本上会在编译(或运行)时将代码注入已编译的程序集中,该程序集将根据您的定义调用您的方法。

    更新
    回复:PostSharp:codeplex 上有很多很好的教程。您需要构建一个继承自 PostSharp.Laos.OnMethodBoundaryAspect 的新属性。覆盖该基类的方法将告诉后编译器在编译期间插入什么代码。 codeplex 上的跟踪示例应该向您展示您需要做的所有事情。
    EndUpdate

    您可能想要查看的另一种架构模式是observer(例如a quick google found this msdn article)

    如果这些方法实际上是某些相关类中的对象行为,那么观察者可能会收到活动通知,然后做出相应的响应。像这样的发布-订阅模式的缺点是您需要向观察者注册您的依赖列表。如果你只是在类上有一堆方法,那么这个概念在某种程度上仍然适用,但不一定是理想的。

    当然,可怜的男人/女人的做法是在所有方法的末尾添加一行代码;-)

    【讨论】:

    • 感谢您的回复!您能否举例说明如何使用 PostSharp 完成我的任务?提前致谢。
    【解决方案2】:

    编辑:

    听起来您正试图通过AOP 做某事。也许像PostSharp 这样的东西会有所帮助——它可以让你通过属性做你想做的事。


    鉴于您发布的类型,请尝试以下操作:

    Imports System
    Imports System.Reflection
    
    Class Program
        Private Shared Sub Main()
            Dim type As Type = GetType(Class1)
            Dim members As MemberInfo() = type.GetMembers()
           
            For Each member As MemberInfo In members
                Dim attributes As Object() = member.GetCustomAttributes(GetType(SampleAttribute), True)
               
                If attributes.Length > 0 Then
                    ' this means that the current "member"
                    ' has your custom attribute
                End If
            Next
        End Sub
    End Class
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多