Skip to content

Commit 44f1c08

Browse files
Bart KoelmanBart Koelman
authored andcommitted
Optimization: resolve property via reflection only once
1 parent 430e128 commit 44f1c08

File tree

1 file changed

+22
-14
lines changed

1 file changed

+22
-14
lines changed

src/CSharpGuidelinesAnalyzer/CSharpGuidelinesAnalyzer/Rules/Naming/PrefixEventHandlersWithOnAnalyzer.cs

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -134,31 +134,39 @@ private static string GetStaticEventTargetName([NotNull] IEventReferenceOperatio
134134
private sealed class PortableEventAssignmentOperation
135135
{
136136
[NotNull]
137-
private readonly IEventAssignmentOperation operation;
137+
private static readonly MethodInfo EventReferencePropertyGetMethod = ResolveEventReferencePropertyGetMethod();
138138

139-
public PortableEventAssignmentOperation([NotNull] IEventAssignmentOperation operation)
140-
{
141-
Guard.NotNull(operation, nameof(operation));
142-
143-
this.operation = operation;
144-
EventReference = TryGetEventReference(operation);
145-
}
139+
[NotNull]
140+
private readonly IEventAssignmentOperation innerOperation;
146141

147142
[CanBeNull]
148-
public IEventReferenceOperation EventReference { get; }
143+
public IEventReferenceOperation EventReference => InvokeEventReferencePropertyGetMethod();
149144

150145
[NotNull]
151-
public IOperation HandlerValue => operation.HandlerValue;
146+
public IOperation HandlerValue => innerOperation.HandlerValue;
152147

153-
public bool Adds => operation.Adds;
148+
public bool Adds => innerOperation.Adds;
154149

155-
[CanBeNull]
156-
private static IEventReferenceOperation TryGetEventReference([NotNull] IEventAssignmentOperation operation)
150+
public PortableEventAssignmentOperation([NotNull] IEventAssignmentOperation operation)
151+
{
152+
Guard.NotNull(operation, nameof(operation));
153+
innerOperation = operation;
154+
}
155+
156+
[NotNull]
157+
private static MethodInfo ResolveEventReferencePropertyGetMethod()
157158
{
158159
// Breaking change in Microoft.CodeAnalysis v2.9:
159160
// type of IEventAssignmentOperation.EventReference was changed from IEventReferenceOperation to IOperation.
161+
160162
PropertyInfo propertyInfo = typeof(IEventAssignmentOperation).GetRuntimeProperty("EventReference");
161-
object propertyValue = propertyInfo.GetMethod.Invoke(operation, Array.Empty<object>());
163+
return propertyInfo.GetMethod;
164+
}
165+
166+
[CanBeNull]
167+
private IEventReferenceOperation InvokeEventReferencePropertyGetMethod()
168+
{
169+
object propertyValue = EventReferencePropertyGetMethod.Invoke(innerOperation, Array.Empty<object>());
162170

163171
return typeof(IEventReferenceOperation).GetTypeInfo().IsAssignableFrom(propertyValue.GetType().GetTypeInfo())
164172
? (IEventReferenceOperation)propertyValue

0 commit comments

Comments
 (0)