我将创建一个包装类,其中既包括您的
List
自定义对象,也包括另一个属性的错误信息。
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();
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)
{
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;}
}
现在,您可以根据需要设置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;
}