填充接口

本文关键字:接口 填充 | 更新日期: 2023-09-27 17:50:35

谁能告诉我如何在我的界面IAccount填充我的字段?我在x.Add(new IAccount ...

中出现错误
public class IPersonRepo : IAccount
{
    string connectionstring = @"Server=SLI002/SQLEXPRESS;Database=atengturonDB;Trusted_Connection=true;";
    public int AccountsID
    {
        get
        {
            throw new NotImplementedException();
        }
        set
        {
            throw new NotImplementedException();
        }
    }
    public byte[] AccountUserName
    {
        get
        {
            throw new NotImplementedException();
        }
        set
        {
            throw new NotImplementedException();
        }
    }
    public byte[] AccountPassword
    {
        get
        {
            throw new NotImplementedException();
        }
        set
        {
            throw new NotImplementedException();
        }
    }
    public byte[] AccountSalt
    {
        get
        {
            throw new NotImplementedException();
        }
        set
        {
            throw new NotImplementedException();
        }
    }
    public void getAccount()
    {
        SqlConnection conn = new SqlConnection(connectionstring);
        using (SqlCommand comm = new SqlCommand())
        {
            List<IAccount> x = new List<IAccount>();
            comm.Connection = conn;
            comm.CommandText = "Select AccountsID,AccountsUserName,AccountsPassword,AccountsSalt from Accounts";
            comm.CommandType = CommandType.Text;
            SqlDataReader reader = null;
            conn.Open();
            comm.ExecuteNonQuery();
            reader = comm.ExecuteReader();
            while (reader.Read())
            {
                x.Add(new IAccount
              {
                  AccountsID = (int)reader["AccountsID"],
                  AccountUserName = (byte[])reader["AccountsUserName"],
                  AccountPassword = (byte[])reader["AccountsPassword"],
                  AccountSalt = (byte[])reader["AccountsSalt"]
              });
            }
            conn.Close();
        }
    }
}

填充接口

请将IPersonRepo重命名为PersonRepo,前缀I表示接口,但显然是类。第二,它看起来不像repo (=repository),而是像Person(但这是有争议的…:))

第三,你正在尝试创建接口-但你必须实现该接口的实例类:

//x.Add(new IAccount
//x.Add(new IPersonRepo
//x.Add(new PersonRepo
x.Add(new Person
          {
              AccountsID = (int)reader["AccountsID"],
              AccountUserName = (byte[])reader["AccountsUserName"],
              AccountPassword = (byte[])reader["AccountsPassword"],
              AccountSalt = (byte[])reader["AccountsSalt"]
          });

第四点也是最后一点,也许你应该看看任何ORM,比如NHibernate或实体框架。我可以帮你,但这是你的决定

首先,在决定类名时永远不要使用I前缀。这不是编译错误,但它非常令人困惑,因为惯例是使用I作为接口名称的前缀。
所以你的类应该叫PersonRepo,而不是IPersonRepo
(但是,您可以将以I开头的类命名为(Ice),只是不要使用I作为前缀)

第二个,你不能实例化接口。您可以使用接口类型的变量,但实例化实际的类:IAccount MyAccount = new PersonRepo();