Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit 6f5e256

Browse files
committed
Use Tuple Key with Type in HasAttributeCached
1 parent 1dfe78c commit 6f5e256

File tree

2 files changed

+22
-5
lines changed

2 files changed

+22
-5
lines changed

src/ServiceStack.Text/PlatformExtensions.cs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -133,10 +133,11 @@ public static MethodInfo GetInstanceMethod(this Type type, string methodName) =>
133133
[MethodImpl(MethodImplOptions.AggressiveInlining)]
134134
public static bool HasAttribute<T>(this MethodInfo mi) => mi.AllAttributes().Any(x => x.GetType() == typeof(T));
135135

136-
private static Dictionary<MemberInfo, bool> hasAttributeCache = new Dictionary<MemberInfo, bool>();
136+
private static Dictionary<Tuple<MemberInfo,Type>, bool> hasAttributeCache = new Dictionary<Tuple<MemberInfo,Type>, bool>();
137137
public static bool HasAttributeCached<T>(this MemberInfo memberInfo)
138138
{
139-
if (hasAttributeCache.TryGetValue(memberInfo, out var hasAttr))
139+
var key = new Tuple<MemberInfo,Type>(memberInfo, typeof(T));
140+
if (hasAttributeCache.TryGetValue(key , out var hasAttr))
140141
return hasAttr;
141142

142143
hasAttr = memberInfo is Type t
@@ -149,12 +150,12 @@ public static bool HasAttributeCached<T>(this MemberInfo memberInfo)
149150
? mi.AllAttributes().Any(x => x.GetType() == typeof(T))
150151
: throw new NotSupportedException(memberInfo.GetType().Name);
151152

152-
Dictionary<MemberInfo, bool> snapshot, newCache;
153+
Dictionary<Tuple<MemberInfo,Type>, bool> snapshot, newCache;
153154
do
154155
{
155156
snapshot = hasAttributeCache;
156-
newCache = new Dictionary<MemberInfo, bool>(hasAttributeCache) {
157-
[memberInfo] = hasAttr
157+
newCache = new Dictionary<Tuple<MemberInfo,Type>, bool>(hasAttributeCache) {
158+
[key ] = hasAttr
158159
};
159160

160161
} while (!ReferenceEquals(

tests/ServiceStack.Text.Tests/ReflectionExtensionTests.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System.Text;
55
using NUnit.Framework;
66
using ServiceStack;
7+
using ServiceStack.DataAnnotations;
78

89
namespace ServiceStack.Text.Tests
910
{
@@ -130,6 +131,21 @@ public void Does_GetCollectionType()
130131
Assert.That(new[] { "" }.Select(x => new TestModel()).GetType().GetCollectionType(), Is.EqualTo(typeof(TestModel)));
131132
}
132133

134+
[EnumAsChar]
135+
public enum CharEnum : int
136+
{
137+
Value1 = 'A',
138+
Value2 = 'B',
139+
Value3 = 'C',
140+
Value4 = 'D'
141+
}
142+
143+
[Test]
144+
public void Can_use_HasAttributeCached()
145+
{
146+
Assert.That(typeof(CharEnum).HasAttributeCached<EnumAsCharAttribute>());
147+
Assert.That(typeof(CharEnum).HasAttribute<EnumAsCharAttribute>());
148+
}
133149
}
134150

135151
public class GenericType<T> { }

0 commit comments

Comments
 (0)