我将创建一个包装类,其中包含您List
的 ofCustomObject
和错误信息作为另一个属性。
public class MyCustomerInfo
{
public List<CustomObject> CustomerList { set;get;}
public string ErrorDetails { set;get;}
public MyCustomerInfo()
{
if(CustomerList==null)
CustomerList=new List<CustomObject>();
}
}
现在我将从我的方法返回这个类的一个对象
public MyCustomerInfo GetCustomerDetails()
{
var customerInfo=new MyCustomerInfo();
// Execute a SQL command
try
{
dr = SQL.Execute(sql);
if(dr != null) {
while(dr.Read()) {
CustomObject c = new CustomObject();
c.Key = dr[0].ToString();
c.Value = dr[1].ToString();
c.Meta = dr[2].ToString();
customerInfo.CustomerList.Add(c);
}
}
else
{
customerInfo.ErrorDetails="No records found";
}
}
catch(Exception ex)
{
//Log the error in this layer also if you need it.
customerInfo.ErrorDetails=ex.Message;
}
return customerInfo;
}
编辑:为了使其更可重用和通用,创建一个单独的类来处理这个是个好主意。我将在我的基类中将其作为属性
public class OperationStatus
{
public bool IsSuccess { set;get;}
public string ErrorMessage { set;get;}
public string ErrorCode { set;get;}
public string InnerException { set;get;}
}
public class BaseEntity
{
public OperationStatus OperationStatus {set;get;}
public BaseEntity()
{
if(OperationStatus==null)
OperationStatus=new OperationStatus();
}
}
并让您参与事务的所有子实体都继承自这个基类。
public MyCustomInfo : BaseEntity
{
public List<CustomObject> CustomerList { set;get;}
//Your constructor logic to initialize property values
}
现在从您的方法中,您可以根据需要设置 OperationStatus 属性的值
public MyCustomInfo GetThatInfo()
{
var thatObject=new MyCustomInfo();
try
{
//Do something
thatObject.OperationStatus.IsSuccess=true;
}
catch(Exception ex)
{
thatObject.OperationStatus.ErrorMessage=ex.Message;
thatObject.OperationStatus.InnerException =(ex.InnerException!=null)?ex.InnerException:"";
}
return thatObject;
}