将枚举类型转换为UIntPtr,但没有编译器警告

本文关键字:编译器 警告 枚举 类型转换 UIntPtr | 更新日期: 2023-09-27 18:02:32

在下面的代码中,Resharper给了我一个警告:Cannot cast expression of type 'Color' to type 'UIntPtr'。(实际上,Resharper认为这是一个实际错误。)

但是,没有编译器警告,并且工作正常。

这看起来像是Resharper的bug。是吗?或者是否存在一些编译器不担心的问题?(我使用Resharper 7.1.1)

using System;
namespace Demo
{
    internal class Program
    {
        public enum Color { Red, Green, Blue }
        private static void Main(string[] args)
        {
            UIntPtr test = (UIntPtr) Color.Red; // Resharper warning, no compile warning.
        }
    }
}

我可以通过先将值转换为int来消除警告,所以我有一个解决方法:

UIntPtr test = (UIntPtr)(int) Color.Red;

将枚举类型转换为UIntPtr,但没有编译器警告

这看起来像是Resharper的bug。是吗?

Yes:

RSRP-78748 False 'conversion does not exist' (UIntPtr)

using System;
class A
{
    static void Main()
    {
        E? x = 0;
        UIntPtr z = (UIntPtr)x;
    }
}
enum E { }

这是一个已知的规格偏差。

自2013-03-05起不固定