Browse Source

Enhance IsDictionary to support more dictionary interfaces

pull/23151/head
maliming 1 year ago
parent
commit
d893d7b3a8
No known key found for this signature in database GPG Key ID: A646B9CB645ECEA4
  1. 25
      framework/src/Volo.Abp.Core/Volo/Abp/Reflection/TypeHelper.cs
  2. 13
      framework/test/Volo.Abp.Http.Tests/Volo/Abp/Http/ApiTypeNameHelper_Tests.cs

25
framework/src/Volo.Abp.Core/Volo/Abp/Reflection/TypeHelper.cs

@ -1,6 +1,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
@ -129,17 +130,22 @@ public static class TypeHelper
public static bool IsDictionary(Type type, out Type? keyType, out Type? valueType)
{
var dictionaryTypes = ReflectionHelper
.GetImplementedGenericTypes(
type,
typeof(IDictionary<,>)
);
var knownDictionaryInterfaces = new Type[]
{
typeof(IDictionary<,>),
typeof(IReadOnlyDictionary<,>),
typeof(IImmutableDictionary<,>)
};
if (dictionaryTypes.Count == 1)
foreach (var dictInterface in knownDictionaryInterfaces)
{
keyType = dictionaryTypes[0].GenericTypeArguments[0];
valueType = dictionaryTypes[0].GenericTypeArguments[1];
return true;
var dictionaryTypes = ReflectionHelper.GetImplementedGenericTypes(type, dictInterface);
if (dictionaryTypes.Count == 1)
{
keyType = dictionaryTypes[0].GenericTypeArguments[0];
valueType = dictionaryTypes[0].GenericTypeArguments[1];
return true;
}
}
if (typeof(IDictionary).IsAssignableFrom(type))
@ -151,7 +157,6 @@ public static class TypeHelper
keyType = null;
valueType = null;
return false;
}

13
framework/test/Volo.Abp.Http.Tests/Volo/Abp/Http/ApiTypeNameHelper_Tests.cs

@ -1,5 +1,6 @@
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Shouldly;
using Volo.Abp.Http.Modeling;
using Volo.Abp.Reflection;
@ -25,6 +26,18 @@ public class ApiTypeNameHelper_Tests
ApiTypeNameHelper.GetTypeName(typeof(CycleClass3)).ShouldBe($"[{TypeHelper.GetSimplifiedName(typeof(CycleClass4))}]");
}
[Fact]
public void IsDictionary_Test()
{
ApiTypeNameHelper.GetSimpleTypeName(typeof(IDictionary<string, decimal>)).ShouldBe("{string:number}");
ApiTypeNameHelper.GetSimpleTypeName(typeof(Dictionary<string, decimal>)).ShouldBe("{string:number}");
ApiTypeNameHelper.GetSimpleTypeName(typeof(IReadOnlyDictionary<string, int>)).ShouldBe("{string:number}");
ApiTypeNameHelper.GetSimpleTypeName(typeof(ReadOnlyDictionary<string, int>)).ShouldBe("{string:number}");
ApiTypeNameHelper.GetSimpleTypeName(typeof(OrderedDictionary<string, long>)).ShouldBe("{string:number}");
ApiTypeNameHelper.GetSimpleTypeName(typeof(SortedDictionary<string, long>)).ShouldBe("{string:number}");
}
class CycleClass : IEnumerable<CycleClass>
{
public IEnumerator<CycleClass> GetEnumerator()

Loading…
Cancel
Save