返回布尔值和错误消息C#
我是一名C#的新开发人员,在创建DLL时遇到了一些问题。我需要创建一个DLL,外部系统将使用它从我的数据库中检索一些信息。基本上,他们会给我发一个ID,我需要发回相关信息。这是我的代码:返回布尔值和错误消息C#,c#,methods,C#,Methods,我是一名C#的新开发人员,在创建DLL时遇到了一些问题。我需要创建一个DLL,外部系统将使用它从我的数据库中检索一些信息。基本上,他们会给我发一个ID,我需要发回相关信息。这是我的代码: public bool GetLotInfo (string SupplierCode, out stLotInfo LotInfo, out string ErrorMessage) { //collect info } 由于方法是布尔值,如何返回字符串ErrorMessage?查看方法签名,只需设置它
public bool GetLotInfo (string SupplierCode, out stLotInfo LotInfo, out string ErrorMessage)
{
//collect info
}
由于方法是布尔值,如何返回字符串ErrorMessage?查看方法签名,只需设置它:
public bool GetLotInfo (string SupplierCode, out stLotInfo LotInfo, out string ErrorMessage)
{
//collect info
//Oops, error:
ErrorMessage = "Something bad happened";
}
这是因为ErrorMessage被声明为out
参数。只需分配:
out
参数是ref
参数的特例;它们是通过引用传递的,必须在方法返回之前进行设置。你可以阅读更多关于他们的信息
在您的情况下,一个可能实现的草图是:
public bool GetLotInfo(string supplierCode, out StLotInfo lotInfo, out string errorMessage)
{
try
{
lotInfo = ... //whatever you need to do
errorMessage = null;
return true;
}
catch (MyExpectedException e) //Put here the specific exceptions you are expecting,
//Try to avoid catching the all encompassing System.Exception
{
errorMessage = e.Message;
lotInfo = null;
return false;
}
finally
{
//any clean up you need to do.
}
}
另外,作为补充建议,请尝试遵循c#命名指南:
StLotInfo
而不是StLotInfo
supplierCode
而不是supplierCode
,errorMessage
而不是errorMessage
,等等StLontInfo
中什么是St
public (bool success, string message, LotInfo lotInfo) GetLotInfo(string SupplierCode)
{
// collect info
return (true, "message lot info retrieved successfully", new LotInfo()); // put actual values here
}
方法调用:
var result = GetLotInfo("test");
WriteLine($"Success: {result.success}");
WriteLine($"Message: {result.message}");
WriteLine($"Lot: {result.lotInfo}");
查看有关元组的更多信息
public (bool success, string message, LotInfo lotInfo) GetLotInfo(string SupplierCode)
{
// collect info
return (true, "message lot info retrieved successfully", new LotInfo()); // put actual values here
}
var result = GetLotInfo("test");
WriteLine($"Success: {result.success}");
WriteLine($"Message: {result.message}");
WriteLine($"Lot: {result.lotInfo}");