gpt4 book ai didi

c# - 类型安全的枚举模式在 C# 6+ 版本中是否仍然可行

转载 作者:行者123 更新时间:2023-11-30 14:47:09 25 4
gpt4 key购买 nike

在 JVM/Groovy 领域工作了几年后,我最近回到了 .NET 世界。

我最喜欢的 C# 日常模式之一曾经是 Type-Safe enum pattern ,我觉得非常方便。回到 C# 我立即开始使用它,但现在我怀疑可能有更好或更可取的模式。

让我想到的是我想在“枚举”中引入一些行为。像这样:

public sealed class TypeSafeEnumWithBehaviour
{
public static readonly TypeSafeEnumWithBehaviour IsLowerCase = new TypeSafeEnumWithBehaviour("IsLowerCase", s => s.All(c => Char.IsLower(c)));
public static readonly TypeSafeEnumWithBehaviour IsUpperCase = new TypeSafeEnumWithBehaviour("IsUpperCase", s => s.All(c => Char.IsUpper(c)));

public readonly string Name;
public readonly Func<string, bool> IsValid;

private TypeSafeEnumWithBehaviour(string targetName, Func<string, bool> validation)
{
Name = targetName;
IsValid = validation;
}

}

测试:

[TestMethod]
public void TestMethod1()
{
Assert.IsTrue(TypeSafeEnumWithBehaviour.IsLowerCase.IsValid("apa"));
Assert.IsTrue(TypeSafeEnumWithBehaviour.IsUpperCase.IsValid("PAPA"));
}

我的组织目前使用的是 C# 6,但 C# 7 变得越来越流行,这让我产生了几个问题。

  1. 当前对类型安全枚举模式的看法是什么?
  2. 它仍然是一个有效的模式吗,尤其是关于序列化/持久化?
  3. 我应该放弃它而选择其他东西吗?

最佳答案

C#(从 7.1 版开始)不支持 sum types ,因此在解决此问题之前,您提供的链接中描述的模式适用于静态检查的封闭世界变体问题的部分解决方案。您可以在 F# 中检查对此的适当语言支持。 .

你的例子有点奇怪:这些选项并不是真正不同的变体。对于"",它们都成立,对于"Aa",它们都不成立。它们实际上并没有形成不同可能性的集合,因此不清楚为什么称它们为枚举。

与 C# 7 语言创新无关的小问题:您应该考虑像这样使用 nameof:

public static readonly TypeSafeEnumWithBehaviour IsLowerCase = new TypeSafeEnumWithBehaviour(nameof(IsLowerCase), s => s.All(c => Char.IsLower(c)));

关于c# - 类型安全的枚举模式在 C# 6+ 版本中是否仍然可行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46606024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com