将 int 转换为枚举

发布于 2024-12-07 13:13:28 字数 481 浏览 4 评论 0原文

我正在尝试在 C++/CLI 帮助程序类中使用通用枚举类型,并且如果强制转换不起作用,我希望它默认为 0。我的问题是 result = (T)0; 不起作用。有办法解决这个问题吗?

错误 1 ​​错误 C2440:“类型转换”:无法从“int”转换为“T”

generic <typename T> where T: value class, Enum
static void SetEnumPropertyValue(String^ value, [Out] T %result)
{
    if (String::IsNullOrEmpty(value))
            false;
    if (!Enum::TryParse<T>(value, true, result))
    {
        result = (T)0;
    }
}

I'm trying to use a generic enum type in a C++/CLI helper class and I want it to default to 0 if the cast doesn't work. My problem is that result = (T)0; doesn't work. Is there a way around this?

Error 1 error C2440: 'type cast' : cannot convert from 'int' to 'T'

generic <typename T> where T: value class, Enum
static void SetEnumPropertyValue(String^ value, [Out] T %result)
{
    if (String::IsNullOrEmpty(value))
            false;
    if (!Enum::TryParse<T>(value, true, result))
    {
        result = (T)0;
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我们的影子 2024-12-14 13:13:28

要么使用:

   result = (T)Enum::ToObject(T::typeid, 0);

要么稍微“丑陋”:

   result = (T)(Object^)0;

Either use:

   result = (T)Enum::ToObject(T::typeid, 0);

or the slightly "uglier":

   result = (T)(Object^)0;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文