Enum properties in CustomClassDefinition.FromClass

This commit is contained in:
Kat 2024-11-19 03:08:04 -08:00
parent 1e41443704
commit 1027b922fe
No known key found for this signature in database
GPG key ID: 11C549BC42DB9B8A
2 changed files with 35 additions and 2 deletions

View file

@ -5,10 +5,25 @@ namespace DotTiled.Tests;
public class FromTypeUsedInLoaderTests
{
private enum TestEnum
{
A,
B,
C
}
[Flags]
private enum TestFlags
{
A = 0b001,
B = 0b010,
C = 0b100
}
private sealed class TestClass
{
public string Name { get; set; } = "John Doe";
public int Age { get; set; } = 42;
public TestEnum Enum { get; set; } = TestEnum.A;
public TestFlags Flags { get; set; } = TestFlags.B | TestFlags.C;
}
[Fact]
@ -82,7 +97,9 @@ public class FromTypeUsedInLoaderTests
],
Properties = [
new StringProperty { Name = "Name", Value = "John Doe" },
new IntProperty { Name = "Age", Value = 42 }
new IntProperty { Name = "Age", Value = 42 },
new EnumProperty { Name = "Enum", PropertyType = "TestEnum", Value = new HashSet<string> { "A" } },
new EnumProperty { Name = "Flags", PropertyType = "TestFlags", Value = new HashSet<string> { "B", "C" } }
]
};
@ -167,7 +184,9 @@ public class FromTypeUsedInLoaderTests
],
Properties = [
new StringProperty { Name = "Name", Value = "John Doe" },
new IntProperty { Name = "Age", Value = 42 }
new IntProperty { Name = "Age", Value = 42 },
new EnumProperty { Name = "Enum", PropertyType = "TestEnum", Value = new HashSet<string> { "A" } },
new EnumProperty { Name = "Flags", PropertyType = "TestFlags", Value = new HashSet<string> { "B", "C" } }
]
};

View file

@ -165,6 +165,20 @@ public class CustomClassDefinition : HasPropertiesBase, ICustomTypeDefinition
return new IntProperty { Name = propertyInfo.Name, Value = (int)propertyInfo.GetValue(instance) };
case Type t when t.IsClass:
return new ClassProperty { Name = propertyInfo.Name, PropertyType = t.Name, Value = GetNestedProperties(propertyInfo.PropertyType, propertyInfo.GetValue(instance)) };
case Type t when t.IsEnum:
var isFlags = t.GetCustomAttributes(typeof(FlagsAttribute), false).Length != 0;
if (isFlags)
{
ISet<string> values = new HashSet<string>();
foreach (var value in t.GetEnumValues())
{
if (((int)value & (int)propertyInfo.GetValue(instance)) != 0) values.Add(t.GetEnumName(value));
}
return new EnumProperty { Name = propertyInfo.Name, PropertyType = t.Name, Value = values };
}
return new EnumProperty { Name = propertyInfo.Name, PropertyType = t.Name, Value = new HashSet<string> { t.GetEnumName(propertyInfo.GetValue(instance)) } };
default:
break;
}