检查给定类型是否是枚举
我正在为 Json.NET 编写一个 JsonConverter,它应该允许我将任何枚举转换为由 [Description] 属性定义的字符串值。
例如:
public enum MyEnum {
[Description("Sunday")] Sunday,
[Description("Monday")] Monday,
[Description("Tuesday")] Tuesday,
[Description("Wednesday")] Wednesday,
[Description("Thursday")] Thursday,
[Description("Friday")] Friday,
[Description("Saturday")] Saturday
}
我已经有了支持 myEnum.Description()
的代码,它显然会返回其字符串描述。
在 JsonConverter 实现中,有一个方法:
public override bool CanConvert(Type objectType)
{
}
我试图弄清楚如何确定 objectType
是否为 Enum
并返回 true,以便转换器知道它可以转换它目的。由于我有许多Enum
,我无法显式检查每个枚举,因此我希望有一种更通用的方法来完成此任务。
I am writing a JsonConverter for Json.NET which should allow me to convert any enum's to a string value defined by a [Description] attribute.
For example:
public enum MyEnum {
[Description("Sunday")] Sunday,
[Description("Monday")] Monday,
[Description("Tuesday")] Tuesday,
[Description("Wednesday")] Wednesday,
[Description("Thursday")] Thursday,
[Description("Friday")] Friday,
[Description("Saturday")] Saturday
}
I already have the code for supporting myEnum.Description()
which will obviously return its string description.
In the JsonConverter implementation, there is this method:
public override bool CanConvert(Type objectType)
{
}
I am trying to figure out how to determine if objectType
is an Enum
and return true so that the converter knows it can convert this object. Since I have many Enum
's, I cannot explicitly check each one so I was hoping for a more generic way of accomplishing this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
IsEnum
属性:Use the
IsEnum
property:Type.IsEnum 是您正在寻找的
Type.IsEnum is what your are looking for
我完全误解了这个问题,因为过于关注 [Description],所以如果您想检查特定枚举是否具有 [description] 属性(以防 json 在没有属性时抛出合适的情况),这是一种可能的检查方法:
I completely misinterpreted the question by focusing too much on the [Description], so in case you ever want to check whether a particular enum has a [description] attribute or not ( in case json throws a fit when there is none ), this is one possible way to check for that: