如何解决System.NullReferenceException - 为什么我不能用 try-catch 绕过它?
我正在尝试调试以下情况。 我有一些这样的常量:
public enum ACCESS_LEVEL
{
[Description("Organization")]
ORGANIZATION = 1,[Description("Group")]
GROUP = 2,[Description("User")]
USER = 3
}
我有一个这样的方法,它应该返回描述字符串:
public static class EnumExtensions
{
public static string GetDescription(this Enum value)
{
var attribute = value.GetType()
.GetField(value.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute),false)
.SingleOrDefault() as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
}
通常这会像 GetDescription(GROUP)
一样被调用并返回“Group”。
我遇到过有人错误编码 GetDescription(0)
的情况。这会导致它抛出 System.NullReferenceException,这似乎是合理的,因为没有零值的常量。在我看来,最后一行旨在通过将无效值作为字符串返回来处理这种情况,但执行永远不会到达该行,因为在我不完全理解的复杂 Linq 语句中抛出了异常.
但这是我的主要问题:我尝试将这段代码放入 try-catch 中,但这也不起作用;异常仍然被抛出,catch 块被忽略。那么为什么 try-catch 不起作用?
我使用的是 Windows 10 和 Visual Studio 16.8.3 以及 .NET 4.8.04084
解决方法
您可以简单地使用空条件运算符 (/* Requests event listening access if absent,potentially prompting */
@available(macOS 10.15,*)
public func CGRequestScreenCaptureAccess() -> Bool
) 来避免异常,如下所示:
?
使用上面的这一行:
public static string GetDescription(this Enum value)
{
var attribute = value.GetType()
.GetField(value.ToString())? // <-- null-conditional operator
.GetCustomAttributes(typeof(DescriptionAttribute),false)
.SingleOrDefault() as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
将 ACCESS_LEVEL a = 0;
var t = a.GetDescription();
设置为 t
尝试使用这个:
public static class EnumExtensions
{
public static string GetDescription(this Enum value)
{
if (value == null) return "None"; // or throw exception
var type = value.GetType();
if (type != typeof(ACCESS_LEVEL)) return "None"; // or throw exception
var field = type.GetField(value.ToString());
if (field == null) return "None"; // or throw exception
var attribute = field.GetCustomAttributes(typeof(DescriptionAttribute),false)
.SingleOrDefault() as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。