我有一個數據庫表與用戶,一些是'代理',一些是'客戶'。在我的C#項目中,我有一個User超類和一個Agent和Client子類。代理和客戶擴展用戶。多態性問題C#
在將用戶對象投射或更改爲代理或客戶端對象時,存在一些基本問題。我不知道爲什麼。這可能很基本,但我不知道什麼是錯的。
public class User
{
public int UserId { get; set; }
public string UserType { get; set; }
public DateTime DateCreated { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public User()
{
}
}
public class Agent : User
{
public string Company { get; set; }
public string CompanyReg { get; set; }
public string SecurityQuestion { get; set; }
public string SecurityAnswer { get; set; }
public string Description { get; set; }
public int AccountBalance { get; set; }
public bool WantsRequests { get; set; }
public string ImageUrl { get; set; }
public Agent()
{
}
}
public class Client : User
{
public string Country { get; set; }
public string IP { get; set; }
public Client()
{
}
}
現在我爲什麼不能做到這一點:
public User GetUser(int userid)
{
User user = new User();
User returnuser = user;
string sql = "SELECT usertype, datecreated, email, name, phone, country, ip, company, companyreg, securityquestion, securityanswer, description, accountbalance, aothcredits, wantsrequests FROM ruser WHERE [email protected]";
try
{
using (SqlConnection con = new SqlConnection(constr))
using (SqlCommand cmd = new SqlCommand(sql))
{
con.Open();
cmd.Connection = con;
cmd.Parameters.Add("@userid", System.Data.SqlDbType.Int).Value = userid;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
user.UserId = userid;
user.UserType = rdr["usertype"].ToString();
user.DateCreated = (DateTime)rdr["datecreated"];
user.Email = rdr["email"].ToString();
user.Name = rdr["name"].ToString();
user.Phone = rdr["phone"].ToString();
string type = rdr.GetString(0);
if (type == "agent")
{
Agent agent = user as Agent;
agent.Company = rdr["company"].ToString();
agent.CompanyReg = rdr["companyreg"].ToString();
agent.SecurityQuestion = rdr["securityQuestion"].ToString();
agent.SecurityAnswer = rdr["securityanswer"].ToString();
agent.Description = rdr["description"].ToString();
agent.AccountBalance = (int)rdr["accountbalance"];
agent.WantsRequests = Convert.ToBoolean(rdr["wantsrequests"]);
returnuser = agent;
}
else //type == "client"
{
Client client = user as Client;
client.Country = rdr["country"].ToString();
client.IP = rdr["ip"].ToString();
returnuser = client;
}
}
}
}
}
catch (SqlException e)
{
throw e;
}
return returnuser;
}
有什麼問題?恐怕你沒有提到這一點。 =) –
您在這裏所做的工作可以通過EntityFramework之類的框架(如果您想使用ORM工具)或LinqToSql(用於較低的DB訪問)完成。有沒有理由不使用它? –
也許Jesper應該重新格式化他的問題。這個問題在他的代碼示例上有說明,但有點不可見;)Btw:如果它是唯一的,你不需要提供默認構造函數(不帶參數的構造函數)。 – Zebi