我的代码中有一个错误列为:' DatabaseLayer':using语句中使用的类型必须可以隐式转换为&System; ID.psispsable'。
我尝试查看MSDN和其他Stack Overflow问题,但我还没有解决错误。我正在使用Visual Studio 2015和.NET Framework 4.5.1。
错误在第56行,但我在错误行上方评论过。以下是我文件中的代码:
public class UserDataAccessLayer : IDisposable
{
public bool Create(string username, string pwd, string email)
{
bool retVal = false;
SqlCommand sqlCmd = new SqlCommand("CreateUser");
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("@Username", username);
sqlCmd.Parameters.AddWithValue("@Pwd", pwd);
sqlCmd.Parameters.AddWithValue("@Email", email);
int result = new DatabaseLayer().ExecuteNonQuery(sqlCmd);
if (result != Int32.MaxValue)
retVal = true;
return retVal;
}
public bool Create(string username, string pwd, string email, int roleId)
{
bool retVal = false;
SqlCommand sqlCmd = new SqlCommand("CreateUser");
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("@Username", username);
sqlCmd.Parameters.AddWithValue("@Pwd", pwd);
sqlCmd.Parameters.AddWithValue("@Email", email);
int result = new DatabaseLayer().ExecuteNonQuery(sqlCmd);
if (result != Int32.MaxValue)
retVal = true;
return retVal;
}
public void Dispose()
{
throw new NotImplementedException();
}
public User GetUserInfo(string username, string pwd)
{
User user = null;
using (DatabaseLayer dbLayer = new DatabaseLayer())
{
SqlCommand sqlCmd = new SqlCommand("GetUserInfo");
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("@Username", username);
sqlCmd.Parameters.AddWithValue("@Pwd", pwd);
user = dbLayer.GetEntityList<User>(sqlCmd).FirstOrDefault();
}
return user;
}
}
答案 0 :(得分:12)
using
阻止:
using (DatabaseLayer dbLayer = new DatabaseLayer())
{
//...
}
本质上是句法的简写(或者至少是合理的接近它):
DatabaseLayer dbLayer = new DatabaseLayer();
try
{
//...
}
finally
{
dbLayer.Dispose();
}
请注意finally
中的最后一行。如果您的对象没有实现IDisposable
那么就无法编译。因此错误。
基本上,您有两种选择:
IDisposable
on your type,或者...... using
阻止。答案 1 :(得分:1)
遵循David的建议,通过取消&#34; using()和try和finally块来修复错误。请参阅下面的更正代码&#34;公共用户GetUserInfo(...)&#34;:
public User GetUserInfo(string username, string pwd)
{
User user = null;
DatabaseLayer dbLayer = new DatabaseLayer();
try
{
SqlCommand sqlCmd = new SqlCommand("GetUserInfo");
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("@Username", username);
sqlCmd.Parameters.AddWithValue("@Pwd", pwd);
user = dbLayer.GetEntityList<User>(sqlCmd).FirstOrDefault();
}
finally
{
dbLayer.Dispose();
}
return user;
}