我有一种情况,我必须根据条件返回不同类型的对象。
为此,我dynamic
在C#4.0中使用了返回类型。
但是我做不到。
public dynamic ValidateUser(string UserName, string Password)
{
string Result = string.Empty;
Employees clsEmployee = new Employees();
Customer clsCustomer = new Customer();
sqlConnection = new SqlConnection(Connection());
command = new SqlCommand("dbo.usp_ValidateUser", sqlConnection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@Username", SqlDbType.VarChar).Value = UserName;
command.Parameters.Add("@Password", SqlDbType.VarChar).Value = Password;
sqlConnection.Open();
SqlParameter newSqlParam = new SqlParameter();
newSqlParam.ParameterName = "@Result";
newSqlParam.SqlDbType = SqlDbType.NVarChar;
newSqlParam.Direction = ParameterDirection.Output;
newSqlParam.Size = 50;
command.Parameters.Add(newSqlParam);
SqlDataReader dr = command.ExecuteReader();
Result = command.Parameters["@Result"].Value.ToString();
if (Result == "Employee")
{
while (dr.Read())
{
clsEmployee.EmployeeId = (int)dr["EmployeeId"];
clsEmployee.EmployeeName = (string)dr["EmployeeName"];
clsEmployee.DepartmentName = (string)dr["DepartmentName"];
clsEmployee.RoleName = (string)dr["RoleName"];
}
return clsEmployee;
}
else if (Result == "Customer")
{
while (dr.Read())
{
clsCustomer.CustomerId = (int)dr["CustomerId"];
clsCustomer.CustomerName = (string)dr["CustomerName"];
clsCustomer.CustomerEmail = (string)dr["CustomerEmail"];
clsCustomer.CustomerMobile = (string)dr["CustomerMobile"];
}
return clsCustomer;
}
//How to return???
}
当我尝试返回病情时,它会抛出我
并非所有代码路径返回值都出错。
有什么办法吗?
只需删除else
部分:
else if (Result == "Customer")
{
while (dr.Read())
{
clsCustomer.CustomerId = (int)dr["CustomerId"];
clsCustomer.CustomerName = (string)dr["CustomerName"];
clsCustomer.CustomerEmail = (string)dr["CustomerEmail"];
clsCustomer.CustomerMobile = (string)dr["CustomerMobile"];
}
return clsCustomer;
}
return Result;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句