Sin*_*rMJ 4 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.PixelFormatMono8) {
bpp = 8; // unreachable warning
}
else if (f7PF == FlyCapture2Managed.PixelFormat.PixelFormatMono16){
bpp = 16;
}
else {
MessageBox.Show("Camera misconfigured"); // unreachable warning
}
}
Run Code Online (Sandbox Code Playgroud)
我知道这段代码是无法访问的,但是我不希望这条消息出现,因为它是编译时的配置,只需要更改常量来测试不同的设置,每像素位数(bpp)会根据像素格式.是否有一个很好的方法让一个变量保持不变,从中导出另一个变量,但不会导致无法访问的代码警告?请注意,我需要两个值,在相机启动时需要将其配置为正确的像素格式,并且我的图像理解代码需要知道图像的位数.
那么,有一个很好的解决方法,还是我只是忍受这个警告?
最好的方法是禁用文件顶部的警告:
#pragma warning disable 0162
Run Code Online (Sandbox Code Playgroud)
另一种方法是将您const转换为static readonly.
private static readonly FlyCapture2Managed.PixelFormat f7PF =
FlyCapture2Managed.PixelFormat.PixelFormatMono16;
Run Code Online (Sandbox Code Playgroud)
但是,如果性能对您的代码很重要,我建议保留它const并禁用警告.虽然const并且static readonly在功能上是等效的,但前者允许更好的编译时优化,否则可能会丢失.
作为参考,您可以通过以下方式将其关闭:
#pragma warning disable 162
Run Code Online (Sandbox Code Playgroud)
..并重新启用:
#pragma warning restore 162
Run Code Online (Sandbox Code Playgroud)
您可以用查找替换条件Dictionary以避免警告:
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");
}
Run Code Online (Sandbox Code Playgroud)