在C#中返回任何类型

Return any Type in C#
2021-06-10
  •  译文(汉语)
  •  原文(英语)

我有一种情况,我必须根据条件返回不同类型的对象.

为此,我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???
}

当我尝试返回病情时,它会抛出我

并非所有代码路径返回值都出错.

有什么办法吗?

速聊1:
您为什么不将身份验证与人口分开到一个单独的类中,或者至少不返回IPerson?dynamic几乎永远不是正确的解决方案.
速聊2:
而不是最后一个else声明,只是return Result;
速聊3:
我强烈怀疑这不是您的实际代码,否则您将不会收到该错误消息.我怀疑您的决赛else实际上是else if或类似的东西.
速聊4:
正如Tim所建议的,我强烈建议使用Interface或某些父类,也许是后来作为客户或Employee继承的User Type类,并且您始终返回User Class对象.
速聊5:
如果结果是意外的,您真的要只返回一个字符串吗?我觉得这很奇怪.像蒂姆一样,我在这里质疑设计.
解决过程1

只需删除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;
解决过程2
switch (Result)
{
    case "Employee":
    {
        ...
        return ...
    }
    case "Customer":
    {
        ...
        return ....
    }
    default:
        return Result;
}
解决过程3

桑索什

这不是处理不同类型的正确方法.您可以考虑实现此目的的接口的实现.这样可以提高可读性和可扩展性.我相信您正在开发支持代码,因此您在实现新实现方面可能会受到限制.

我想你可以这样改变

public object ValidateUser(string UserName, string Password)
{
    object retVal= null;
    string Result = String.Empty;

    Employees clsEmployee = new Employees();
    Customer clsCustomer = new Customer();

    // get the data
    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"];
        }

        retVal=clsEmployee;
    }
   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"];
        }

        retVal=clsCustomer;
    }
     retVal=Result;
     return retVal;
    }

我认为这将消除当前的问题.

I have a scenario where i have to return different type of objects according to a condition.

For that i have used dynamic return type in c# 4.0.

But i couldn't achieve that.

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???
}

When i try to return inside the condition it throws me

Not all code path return value' error.

Any solutions?

Talk1:
Why don't you either split authentication into a separate class from population, or at least return IPerson? dynamic is almost never the correct solution.
Talk2:
Instead of having the last else statement, just return Result;
Talk3:
I strongly suspect this isn't your actual code, otherwise you wouldn't have got that error message. I suspect your final else is actually an else if or something like that.
Talk4:
As Tim suggest, I strongly suggest to use Interface or some parent class, Maybe a User Type class that later got inherited as customer or Employee, and you always return User Class object.
Talk5:
And do you really want to return just a string if the result is unexpected? That seems highly odd to me. Like Tim, I question the design here.
Solutions1

Just remove the else part:

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;
Solutions2
switch (Result)
{
    case "Employee":
    {
        ...
        return ...
    }
    case "Customer":
    {
        ...
        return ....
    }
    default:
        return Result;
}
Solutions3

Santhosh,

This is not a proper way to handle different types. You could consider the implementation of an interface to achieve this. This make more readability and much more extensible. I believe that you are working on a support code, so that you may have limitation for achieving the new implementation.

I think you could change like this

public object ValidateUser(string UserName, string Password)
{
    object retVal= null;
    string Result = String.Empty;

    Employees clsEmployee = new Employees();
    Customer clsCustomer = new Customer();

    // get the data
    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"];
        }

        retVal=clsEmployee;
    }
   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"];
        }

        retVal=clsCustomer;
    }
     retVal=Result;
     return retVal;
    }

I think this will eliminates the current problem.

转载于:https://stackoverflow.com/questions/19064291/return-any-type-in-c-sharp

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入