我有一個場景,我必須根據條件返回不同類型的對象。返回任何類型的C#
爲此,我在c#4.0中使用了dynamic
返回類型。
但我無法做到這一點。
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???
}
當我嘗試的條件內返回它拋出我
並非所有的代碼路徑返回值」的錯誤。
任何解決方案?
爲什麼不把認證分成單獨的一個類,或者至少返回'IPerson'? 「動態」幾乎從來都不是正確的解決方案。 –
而不是有最後的'else'語句,只是'返回結果;' –
我強烈懷疑這不是你的實際代碼,否則你不會得到那個錯誤信息。我懷疑你最後的'else'實際上是一個'else if'或類似的東西。 –