Files
GoakeFlax/Source/Game/Console/ConsoleVariable.cs
2022-05-14 19:10:13 +03:00

75 lines
2.0 KiB
C#

using System;
using System.Reflection;
namespace Game
{
[Flags]
public enum ConsoleFlags
{
NoSerialize = 1, // Value does not persist
Alias = NoSerialize
}
internal struct ConsoleVariable
{
public string name { get; }
public ConsoleFlags flags { get; }
private readonly FieldInfo field;
private readonly MethodInfo getter;
private readonly MethodInfo setter;
public ConsoleVariable(string name, ConsoleFlags flags, FieldInfo field)
{
this.name = name;
this.flags = flags;
this.field = field;
getter = null;
setter = null;
}
public ConsoleVariable(string name, ConsoleFlags flags, MethodInfo getter, MethodInfo setter)
{
this.name = name;
this.flags = flags;
field = null;
this.getter = getter;
this.setter = setter;
}
public string GetValueString()
{
Type type = field != null ? field.FieldType : getter.ReturnType;
if (type == typeof(string))
{
if (field != null)
return (string)field.GetValue(null);
if (setter != null)
return (string)getter.Invoke(null, null);
}
else
{
throw new Exception("cvar is not type of string");
}
throw new Exception("GetValueString no field or getter specified");
}
public void SetValue(string value)
{
Type type = field != null ? field.FieldType : getter.ReturnType;
if (type == typeof(string))
{
if (field != null)
field.SetValue(null, value);
else if (setter != null)
setter.Invoke(null, new object[] { value });
}
else
{
throw new Exception("Unsupported type for SetValue: " + type.Name);
}
}
}
}