在C#中将Int转换成通用枚举 [英] Cast Int to Generic Enum in C#
本文介绍了在C#中将Int转换成通用枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
类似于将int转换为C#中的枚举,但我的枚举是一个Generic Type参数。
Similar to Cast int to enum in C# but my enum is a Generic Type parameter. What is the best way to handle this?
示例:
private T ConvertEnum<T>(int i) where T : struct, IConvertible
{
return (T)i;
}
生成编译器错误无法将类型'int'转换为'T'
完整的代码如下,其中value可以包含int或null。
Full code is as follows, where value can contain the int, or null.
private int? TryParseInt(string value)
{
var i = 0;
if (!int.TryParse(value, out i))
{
return null;
}
return i;
}
private T? TryParseEnum<T>(string value) where T : struct, IConvertible
{
var i = TryParseInt(value);
if (!i.HasValue)
{
return null;
}
return (T)i.Value;
}
推荐答案
我找到的最简单的方法是通过向对象
添加一个转换来强制编译器的手。
The simplest way I have found is to force the compiler's hand by adding a cast to object
.
return (T)(object)i.Value;
这篇关于在C#中将Int转换成通用枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文