C # 默认将 Enum 设置为 0。因此,除非第一个 Enum 成员实际上是默认值,否则直觉上不会将其映射到 0。
允许强制执行 Web API 所需的枚举
考虑以下最小 Web API:
using Microsoft.AspNetCore.Mvc;
using MiniValidation; // See https://github.com/dotnet/aspnetcore/issues/39063
using System.ComponentModel.DataAnnotations;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// Returns true if validation is successful, false otherwise
app.MapGet("/", ([FromBody] MyClass myClass) => MiniValidator.TryValidate(myClass, out _));
app.Run();
class MyClass
{
[EnumDataType(typeof(MyEnum))] // Validates `MyEnum` is a valid enum value
public MyEnum MyEnum { get; set; }
}
enum MyEnum { One, Two }