C# 调用对象时发生未处理的异常
我构建了以下类:C# 调用对象时发生未处理的异常,c#,.net,unhandled-exception,C#,.net,Unhandled Exception,我构建了以下类: public class FSCServerLocator { public string userLocation { get; private set; } public string FSCServer { get { switch (userLocation) {
public class FSCServerLocator
{
public string userLocation { get; private set; }
public string FSCServer
{
get
{
switch (userLocation)
{
default:
return @"\\himgwsfs01\QT_Tools\Diagnose\09_SWT_FSCs";
}
}
}
public FSCServerLocator(string location)
{
if (string.IsNullOrWhiteSpace(userLocation))
{
throw new Exception("No location included at initialization");
}
//parameter filtering
userLocation = location;
}
}
}
像这样调用对象
var fscServerLocator = new FSCServerLocator(@"\\himgwsfs01\QT_Tools\Diagnose\09_SWT_FSCs");
运行程序时,会抛出一个未处理的异常,说明{“初始化时未包含任何位置”}
。
我只想看看是否到达了位置,但可能我遗漏了什么,因为我是c#的新手。为了避免此异常,您需要将构造函数更改为查看位置,而不是用户位置(见下文):
public FSCServerLocator(string location)
{
if (string.IsNullOrWhiteSpace(location))
{
throw new Exception("No location included at initialization");
}
//parameter filtering
userLocation = location;
}
或
在构造函数中设置对象之前,您试图使用该对象的参数。您可以先设置它,也可以根据要设置它的参数进行测试。如果(string.IsNullOrWhiteSpace(userLocation))您使用的是
userLocation
而不是参数location
。这不能缩短吗?用户位置=位置??抛出新异常(“初始化时未包含位置”);从个人角度来看,我更喜欢将验证和分配分开。还需要注意的是,OP正在寻找StringIsNullOrWhiteSpace,而不仅仅是null(即??)
public FSCServerLocator(string location)
{
//parameter filtering
userLocation = location;
if (string.IsNullOrWhiteSpace(userLocation))
{
throw new Exception("No location included at initialization");
}
}
public FSCServerLocator(string location)
{
if (string.IsNullOrWhiteSpace(location))
{
throw new Exception("No location included at initialization");
}
//parameter filtering
userLocation = location;
}