Merge pull request #140 from RogueException/khio-enumpatch

Enum TypeReader
This commit is contained in:
RogueException
2016-07-20 22:45:34 -03:00
committed by GitHub
2 changed files with 67 additions and 2 deletions

View File

@@ -77,11 +77,22 @@ namespace Discord.Commands
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsEnum)
type = Enum.GetUnderlyingType(type);
Module.Service.AddTypeReader(type, new EnumTypeReader(type));
var reader = Module.Service.GetTypeReader(type);
if (reader == null)
throw new InvalidOperationException($"{type.FullName} is not supported as a command parameter, are you missing a TypeReader?");
{
if (typeInfo.IsEnum)
{
type = Enum.GetUnderlyingType(type);
reader = Module.Service.GetTypeReader(type);
}
if (reader == null)
throw new InvalidOperationException($"{type.FullName} is not supported as a command parameter, are you missing a TypeReader?");
}
bool isUnparsed = parameter.GetCustomAttribute<UnparsedAttribute>() != null;
if (isUnparsed)

View File

@@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Discord.Commands
{
internal class EnumTypeReader : TypeReader
{
private readonly Dictionary<string, object> stringValues;
private readonly Dictionary<int, object> intValues;
private readonly Type enumType;
public override Task<TypeReaderResult> Read(IMessage context, string input)
{
int inputAsInt;
object enumValue;
if (int.TryParse(input, out inputAsInt))
{
if (intValues.TryGetValue(inputAsInt, out enumValue))
return Task.FromResult(TypeReaderResult.FromSuccess(enumValue));
else
return Task.FromResult(TypeReaderResult.FromError(CommandError.CastFailed, $"Value is not a {enumType.Name}"));
}
else
{
if (stringValues.TryGetValue(input.ToLower(), out enumValue))
return Task.FromResult(TypeReaderResult.FromSuccess(enumValue));
else
return Task.FromResult(TypeReaderResult.FromError(CommandError.CastFailed, $"Value is not a {enumType.Name}"));
}
}
public EnumTypeReader(Type type)
{
enumType = type;
var stringValuesBuilder = new Dictionary<string, object>();
var intValuesBuilder = new Dictionary<int, object>();
var values = Enum.GetValues(enumType);
foreach (var v in values)
{
stringValuesBuilder.Add(v.ToString().ToLower(), v);
intValuesBuilder.Add((int)v, v);
}
stringValues = stringValuesBuilder;
intValues = intValuesBuilder;
}
}
}