C# 使用常量变量检测到无法访问的代码

C# 使用常量变量检测到无法访问的代码,c#,unreachable-code,C#,Unreachable Code,我有以下代码: private const FlyCapture2Managed.PixelFormat f7PF = FlyCapture2Managed.PixelFormat.PixelFormatMono16; public PGRCamera(ExamForm input, bool red, int flags, int drawWidth, int drawHeight) { if (f7PF == FlyCapture2Managed.PixelFormat.PixelF

我有以下代码:

private const FlyCapture2Managed.PixelFormat f7PF = FlyCapture2Managed.PixelFormat.PixelFormatMono16;

public PGRCamera(ExamForm input, bool red, int flags, int drawWidth, int drawHeight) {
   if (f7PF == FlyCapture2Managed.PixelFormat.PixelFormatMono8) {
      bpp = 8;  // unreachable warning
   }
   else if (f7PF == FlyCapture2Managed.PixelFormat.PixelFormatMono16){
      bpp = 16;
   }
   else {
      MessageBox.Show("Camera misconfigured");  // unreachable warning
   }
}
我知道这段代码是不可访问的,但我不希望出现这条消息,因为这是一个编译配置,只需要更改常量来测试不同的设置,并且每像素位(bpp)根据像素格式而变化。有没有一种好方法可以让一个变量保持常量,从中派生另一个变量,但不会导致无法访问的代码警告?请注意,我需要这两个值,在相机启动时,它需要配置为正确的像素格式,我的图像理解代码需要知道图像的位数


那么,是否有一个好的解决方法,或者我只是接受这个警告?

最好的方法是禁用文件顶部的警告:

#pragma warning disable 0162
另一种方法是将
常量
转换为
静态只读

private static readonly FlyCapture2Managed.PixelFormat f7PF = 
                        FlyCapture2Managed.PixelFormat.PixelFormatMono16;

但是,如果性能对代码很重要,我建议将其保持为
const
,并禁用警告。虽然
const
static readonly
在功能上是等效的,但前者允许更好的编译时优化,否则可能会丢失。

作为参考,您可以通过以下方式将其关闭:

#pragma warning disable 162
..并通过以下方式重新启用:

#pragma warning restore 162

这是可能的,只需添加

#杂注警告禁用0162

在你的领域之前。要恢复,请将其结束


#杂注警告恢复0162
。此处的更多信息

您可以使用
字典
查找替换条件,以避免出现警告:

private static IDictionary<FlyCapture2Managed.PixelFormat,int> FormatToBpp =
    new Dictionary<FlyCapture2Managed.PixelFormat,int> {
        {FlyCapture2Managed.PixelFormat.PixelFormatMono8, 8}
    ,   {FlyCapture2Managed.PixelFormat.PixelFormatMono16, 16}
    };
...
int bpp;
if (!FormatToBpp.TryGetValue(f7PF, out bpp)) {
    MessageBox.Show("Camera misconfigured");
}
专用静态IDictionary FormatToBpp=
新词典{
{FlyCapture2Managed.PixelFormat.PixelFormatMono8,8}
,{FlyCapture2Managed.PixelFormat.PixelFormatMono16,16}
};
...
int-bpp;
如果(!formatToApp.TryGetValue(f7PF,输出bpp)){
MessageBox.Show(“摄像头配置错误”);
}

不确定总体方法是否最佳,但您可以使用switch语句,并在
默认值:
块中出现错误。我支持
静态只读
选项。在这种情况下,性能似乎不是一个问题。这可能不是最有效的,但肯定是最优雅的。