gpt4 book ai didi

c# - Lance Hunt 的 C# 编码标准 - 枚举混淆

转载 作者:可可西里 更新时间:2023-11-01 03:12:12 26 4
gpt4 key购买 nike

我的团队最近开始使用 Lance Hunt's C# Coding Standards文档作为巩固我们的编码标准的起点。

有一项我们只是不明白其中的要点,这里的任何人都可以阐明它吗?

该项目是编号 77:

Always validate an enumeration variable or parameter value before consuming it. They may contain any value that the underlying Enum type (default int) supports.

Example:

public void Test(BookCategory cat)
{
if (Enum.IsDefined(typeof(BookCategory), cat))
{…}
}

最佳答案

要点是您可能希望通过 BookCategory 类型的参数,您总是有一个有意义 的图书类别。事实并非如此。我可以打电话:

BookCategory weirdCategory = (BookCategory) 123456;
Test(weirdCategory);

如果枚举旨在表示一组众所周知的值,则不应期望代码明智地处理该众所周知的集合之外的值。测试首先检查参数是否合适。

不过我个人会颠倒逻辑:

public void Test(BookCategory cat)
{
if (!Enum.IsDefined(typeof(BookCategory), cat))
{
throw new ArgumentOutOfRangeException("cat");
}
}

在 C# 3 中,这可以通过扩展方法轻松完成:

// Can't constrain T to be an enum, unfortunately. This will have to do :)
public static void ThrowIfNotDefined<T>(this T value, string name) where T : struct
{
if (!Enum.IsDefined(typeof(T), value))
{
throw new ArgumentOutOfRangeException(name);
}
}

用法:

public void Test(BookCategory cat)
{
cat.ThrowIfNotDefined("cat");
}

关于c# - Lance Hunt 的 C# 编码标准 - 枚举混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/594378/

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