gpt4 book ai didi

c# - 检查枚举属性中是否为 null

转载 作者:行者123 更新时间:2023-12-02 13:16:32 25 4
gpt4 key购买 nike

我有一个枚举属性,用于填充下拉列表作为表单的一部分,如下所示:

 public class MyModel
{
[Required]
[DisplayName("Type of Enum")]
public EnumType? Type { get; set; }
}

public enum EnumType
{
option1 = 1,
option2 = 2,
option3 = 3,
option4 = 4
}

表单提交到另一个 Controller ,我在其中尝试检查枚举类型中的 null :

 public class ResultController : Controller
{
// GET: Result
[AllowAnonymous]
public ActionResult Index(MyModel model)
{
if(!Enum.IsDefined(typeof(MyEnum), model.EnumType))
{
return RedirectToAction("Index", "Home");
}
return View();
}
}

当我尝试 ..../result?Type=5 RedirectToAction 有效,但是当我尝试 ..../result?Type= 我得到 ArgumentNullException

注意:在枚举中添加 None=0 对我来说不是一个选项,我不希望下拉列表中没有显示任何内容。

如何检查 Controller 中的空值?这方面有最佳实践吗?

最佳答案

IsDefined() 中使用该值之前,请显式检查该值是否为 null

public ActionResult Index(MyModel model)
{
if(!model.EnumType.HasValue)
{
return RedirectToAction("Index", "Home");
}
if(!Enum.IsDefined(typeof(MyEnum), model.EnumType))
{
return RedirectToAction("Index", "Home");
}
return View();
}

更短的版本是使用 null-coalesce operator在调用 IsDefined() 时使用 0 而不是 null:

public ActionResult Index(MyModel model)
{
if(!Enum.IsDefined(typeof(MyEnum), model.EnumType ?? 0))
{
return RedirectToAction("Index", "Home");
}
return View();
}

关于c# - 检查枚举属性中是否为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40354003/

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