C# 异常:指定的强制转换无效

C# 异常:指定的强制转换无效,c#,casting,C#,Casting,当我放置断点并调试时,错误来自这一行 public class UserLoginInfo { public UserRole Role; public string Username; public static UserLoginInfo FetchUser(string username, string password) { using (var connection = Utils.Database.GetConnection())

当我放置断点并调试时,错误来自这一行

public class UserLoginInfo
{
    public UserRole Role;
    public string Username;

    public static UserLoginInfo FetchUser(string username, string password)
    {
        using (var connection = Utils.Database.GetConnection())
        using (var command = new SqlCommand("SELECT [Username], [Password], [Role] FROM [Users] WHERE [Username] = @username", connection))
        {
            command.Parameters.AddWithValue("@username", username);
            using (var reader = command.ExecuteReader())
            {
                if (reader == null || !reader.Read() || !Utils.Hash.CheckPassword(username, password, (byte[])reader["Password"]))
                    throw new Exception("Wrong username or password.");

                return new UserLoginInfo { Username = (string)reader["Username"], Role = (UserRole)reader["Role"] };
            }
        }
    }
}
我不明白为什么我会犯这个错误。请帮帮我

编辑:如何将(字符串)阅读器[“角色”]转换为用户角色

return 
    new UserLoginInfo 
    { 
        Username = (string)reader["Username"], 
        Role = (UserRole)reader["Role"] 
    };

代码可能在以下方面失败:

public enum UserRole
{
    Admin,
    Maintance,
    User
}
因为您试图将
对象
强制转换为
用户角色
,而强制转换不存在

看起来您正试图将
reader[“Role”]
转换为
UserRole
对象,我猜这就是失败的原因

您需要指定(或实现)一个有效的强制转换,或者实现类似于
UserRole.Parse(string value)
的功能,将字符串解析为有效的
UserRole
对象

Role = (UserRole)reader["Role"];
假定
UserRole
是您定义的一种类型,因此
SqlDataReader
不知道如何将从数据库获取的数据转换为这种类型。数据库中此列的类型是什么

编辑:对于更新的问题,您可以执行以下操作:

Role = (UserRole)reader["Role"]

您可能需要添加一些额外的错误检查,例如检查
role
是否不为null。此外,在解析枚举之前,您可以使用检查解析是否有效。

(UserRole)reader[“Role”]
应该是
(string)reader[“Role”]
。SQL server中没有
UserRole
类型。

这意味着您不能强制转换
(字符串)读卡器[“用户名”]
(不太可能),或
(UserRole)读卡器[“角色”]
(更可能)。什么是
UserRole
-您可以通过从db结果强制转换来创建它吗?您是否需要类似于
newuserrole(reader[“Role”])

如果数据库中存储的是
字符串,但您希望将其转换为
枚举类型,则应使用

例如:

var role = (string)reader["Role"];
UserRole role = (UserRole)Enum.Parse( typeof(UserRole), role );
可能
(UserRole)Enum.Parse(typeof(UserRole),(string)reader[“Role”])
是最受欢迎的答案,而且,令我惊讶的是,它还能工作!!(令人惊讶的是,考虑到数据库中的枚举值存储为整数,Enum.Parse方法甚至可以将整数的字符串表示形式正确地转换为相应的枚举值)。但这是我经常做的,切中要害的是:

UserRole userRole = (UserRole) Enum.Parse(typeof(UserRole), (string) reader["Role"]);

这应该会更有效,但在现实生活中不会引人注目。

您为UserRole做了一个演员阵容。你也需要为用户名做一个吗?请参阅我更新的答案,了解如何转换为枚举值。顺便问一下,为什么你的
角色
用户名
成员是公共的?您至少应该使用
public UserRole{get;set;}
将它们转换为autoprops。
UserRole role = (UserRole)Convert.ToInt32(reader["Role"]);