78 lines
2.6 KiB
C#
78 lines
2.6 KiB
C#
using System;
|
|
using System.Reflection;
|
|
|
|
namespace Game
|
|
{
|
|
internal struct ConsoleCommand
|
|
{
|
|
public string name { get; }
|
|
|
|
private readonly MethodInfo[] methods;
|
|
|
|
public ConsoleCommand(string name, MethodInfo[] method)
|
|
{
|
|
this.name = name;
|
|
methods = method;
|
|
}
|
|
|
|
public void Invoke()
|
|
{
|
|
foreach (MethodInfo method in methods)
|
|
{
|
|
var methodParameters = method.GetParameters();
|
|
if (methodParameters.Length == 0)
|
|
method.Invoke(null, null);
|
|
else if (methodParameters.Length == 1 && methodParameters[0].ParameterType == typeof(string[]))
|
|
method.Invoke(null, new object[] { Array.Empty<string>() });
|
|
else
|
|
continue;
|
|
return;
|
|
}
|
|
|
|
throw new Exception("Unexpected number of parameters.");
|
|
}
|
|
|
|
public void Invoke(string[] parameters)
|
|
{
|
|
MethodInfo match = null;
|
|
foreach (MethodInfo method in methods)
|
|
{
|
|
var methodParameters = method.GetParameters();
|
|
if (methodParameters.Length == 1 && methodParameters[0].ParameterType == typeof(string[]))
|
|
{
|
|
match = method;
|
|
continue;
|
|
}
|
|
|
|
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.");
|
|
}
|
|
}
|
|
} |