我是 c# 新手,遇到警告说:检测到无法访问的代码
我有一个构建构造函数的类,如下所示:
public class FSC
{
public string cps { get; private set; }
public Database database;
public string Type { get; private set; }
public string Project
{
get
{
switch (Convert.ToInt32(Type))
{
case 2:
return "Evo";
case 1:
return "NBT";
default: return string.Empty;
}
}
}
public FSC(string CPS, FSCServerLocator fscLoc)
{
if (string.IsNullOrWhiteSpace(CPS))
{
throw new Exception("No vin provided at initialization");
//parameter filtering
cps = CPS;
}
}
}
警告触发于cps=CPS;
也许这不是一个大不了的警告,但我认为这将有助于我的理解。谢谢!
由于每次以下
string.IsNullOrWhiteSpace(CPS)
是true
,你抛出一个异常:
throw new Exception("No vin provided at initialization");
无法访问后面的赋值,因为当引发异常时,程序会突然停止。
您可能需要的如下:
public FSC(string CPS, FSCServerLocator fscLoc)
{
if (string.IsNullOrWhiteSpace(CPS))
{
throw new Exception("No vin provided at initialization");
}
cps = CPS;
}
这样,当CPS
为 null、空或空格时,您会引发异常,并且您不会继续创建对象。
为了避免此异常,您需要将构造函数更改为以下代码:
public FSC(string CPS, FSCServerLocator fscLoc)
{
if (string.IsNullOrWhiteSpace(CPS))
{
throw new Exception("No vin provided at initialization");
}
//parameter filtering
cps = CPS;
}
编辑请参阅下面的注释代码,为什么抛出此异常
public FSC(string CPS, FSCServerLocator fscLoc)
{
if (string.IsNullOrWhiteSpace(CPS))
{
// the exception is being thrown here.
throw new Exception("No vin provided at initialization");
// any code below will not be reached.
// closing the bracket before the following statement fixes the "unreachable" code issue.
cps = CPS;
}
}
您正在抛出一个异常,该异常将在设置 cps 之前停止执行。这导致了您的问题。你应该把 cps = CPS 放在你的投掷上方。
简单地说,如果你抛出一个Exception
,你就不能继续执行代码,除非你在调用方法中(或更靠上链)try
-catch
。在此阶段,您可以处理进一步的处理,例如日志记录。
想想当抛出NullReferenceException
时会发生什么。以后的代码将不会执行。
此警告消息只是警告您,永远不会到达抛出操作后出现的代码。这不是错误,而只是一个警告,您的程序将独立编译为此警告。这只是一个通知,让您知道此代码永远不会继续。
查看您的代码:
if (string.IsNullOrWhiteSpace(CPS))
{
throw new Exception("No vin provided at initialization");
//parameter filtering
cps = CPS;
}
当你抛出异常时,它将退出函数,因此抛出后的行永远不会运行。
这应该会删除您的警告。您拥有它的原因是,只有在满足 if 语句中的条件时才会分配 cps。
public FSC(string CPS, FSCServerLocator fscLoc)
{
if (string.IsNullOrWhiteSpace(CPS))
{
throw new Exception("No vin provided at initialization");
}
cps = CPS; //parameter filtering
}
要么:
public FSC(string CPS, FSCServerLocator fscLoc)
{
if (string.IsNullOrWhiteSpace(CPS))
{
//parameter filtering
// other process here if any
cps = CPS;
throw new Exception("No vin provided at initialization");
}
}
或
public FSC(string CPS, FSCServerLocator fscLoc)
{
if (string.IsNullOrWhiteSpace(CPS))
{
//parameter filtering
throw new Exception("No vin provided at initialization");
}
// other process here if any
cps = CPS;
}