Files
GoakeFlax/Source/Game/Cabrito/Console/ConsoleCommand.cs
2021-06-28 16:22:20 +03:00

81 lines
1.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Cabrito
{
internal struct ConsoleCommand
{
public string name { get; private set; }
private MethodInfo[] methods;
public ConsoleCommand(string name, MethodInfo[] method)
{
this.name = name;
this.methods = method;
}
public void Invoke()
{
foreach (var method in methods)
{
var methodParameters = method.GetParameters();
if (methodParameters.Length != 0)
continue;
method.Invoke(null, null);
return;
}
throw new Exception("Unexpected number of parameters.");
}
public void Invoke(string[] parameters)
{
MethodInfo match = null;
foreach (var method in methods)
{
var methodParameters = method.GetParameters();
if (methodParameters.Length == 1 && methodParameters[0].ParameterType == typeof(string[]))
{
match = method;
continue;
}
else if (methodParameters.Length != parameters.Length)
continue;
// TODO: try to parse string parameters to needed types first,
// may require finding the exact match first instead of first matching one.
for (int i = 0; i < methodParameters.Length; i++)
//if (methodParameters[i].ParameterType != parameters[i].GetType())
if (methodParameters[i].ParameterType != typeof(string))
continue;
if (match != null)
{
// Prefer exact number of parameters over string[] match
if (methodParameters.Length != parameters.Length)
continue;
}
match = method;
}
if (match != null)
{
if (match.GetParameters().Length == 1 && match.GetParameters()[0].ParameterType == typeof(string[]))
match.Invoke(null, new object[] {parameters});
else
match.Invoke(null, parameters);
return;
}
throw new Exception("Unexpected number of parameters.");
}
}
}