我想将属性(例如<DebuggerBrowsable(DebuggerBrowsableState.Never)>
)应用于类中的所有私有字段。
如何使用PostSharp完成此操作?
我尝试将以下方面应用于课程,但没有成功。
<MulticastAttributeUsage(MulticastTargets.Class)>
<Serializable>
Public Class DebuggerBrowsableHidePrivateMembersAttribute
Inherits TypeLevelAspect
Implements IAspectProvider
Public Iterator Function ProvideAspects(targetElement As Object) As IEnumerable(Of AspectInstance) Implements IAspectProvider.ProvideAspects
Dim targetType = targetElement.GetType
Dim aspect = New CustomAttributeIntroductionAspect(New ObjectConstruction(targetType, DebuggerBrowsableState.Never))
For Each field In targetType.GetFields(BindingFlags.NonPublic Or BindingFlags.DeclaredOnly)
Yield New AspectInstance(field, aspect)
Next
End Function
End Class
答案 0 :(得分:1)
我最终使用了以下方面:
Imports PostSharp.Aspects
Imports PostSharp.Extensibility
Imports PostSharp.Reflection
<MulticastAttributeUsage(MulticastTargets.Field Or MulticastTargets.Property)>
Public NotInheritable Class DebuggerBrowsableHideMembersAttribute
Inherits LocationLevelAspect
Implements IAspectProvider
'Hides the following members from browsable debugger windows.
' Private Fields
' Protected Fields
' Static (Shared) Fields
' Private Properties
' Protected Properties
' Static (Shared) Properties
' Indexed Properties
Private Shared ReadOnly Aspect As New CustomAttributeIntroductionAspect(New ObjectConstruction(GetType(DebuggerBrowsableAttribute), DebuggerBrowsableState.Never))
Public Iterator Function ProvideAspects(targetElement As Object) As IEnumerable(Of AspectInstance) Implements IAspectProvider.ProvideAspects
Dim location = DirectCast(targetElement, LocationInfo)
Select Case location.LocationKind
Case LocationKind.Field
Dim info = location.FieldInfo
If info.IsPrivate OrElse info.IsFamily OrElse info.IsStatic Then
Yield New AspectInstance(location.FieldInfo, Aspect)
End If
Case LocationKind.Property
Dim info = location.PropertyInfo.GetMethod
If info.IsPrivate OrElse info.IsFamily OrElse info.IsStatic OrElse info.GetParameters.Count > 0 Then
Yield New AspectInstance(location.PropertyInfo, Aspect)
End If
End Select
Exit Function
End Function
End Class