2017-01-11 19 views
0

我正在創建一個接口,並且我要求它能夠處理不同的列表類型,我應該使用什麼?接口中的通用列表

我使用,我在List<Person>List<Charge>列表使用類,List<Other>

我也嘗試這個接口,但它不是正確的泛型列表類型,或類型我使用

interface iGeneric 
{ 
    void Add(object obj); 
    void Delete(object obj); 
    void Update(object obj); 
    object View(object obj); 
} 

而充電類繼承iGeneric接口

public class Charge : iGeneric 
{ 
    public Charge() 
    { 
     Description = "na"; 
    } 

public void Add(object obj) 
    { 
     //Add a new charge to the database 
     List<Charge> myCharge = new List<Charge>(); 
     string cn = ConfigurationHelper.getConnectionString("Scratchpad"); 

     using (SqlConnection con = new SqlConnection(cn)) 
     { 
      con.Open(); 

      try 
      { 
       using (SqlCommand command = new SqlCommand("INSERT INTO tblCharge ([Description],[Amount]) VALUES (@Description, @Amount)", con)) 
       { 
        command.Parameters.Add(new SqlParameter("Description", NewCharge.Description)); 
        command.Parameters.Add(new SqlParameter("Amount", NewCharge.Amount)); 

        command.ExecuteNonQuery(); 
       } 
       MessageBox.Show("New Charge added successfully"); 
      } 
      catch (Exception) 
      { 
       Console.WriteLine("Failed to insert new charge."); 
      } 
     } 

理想情況下,我想設置每個列表和類,當我定義e列表,即

List<Charge> myCharge = new List<Charge>(); 
List<Person> myPerson = new List<Person>(); 
List<Other> myOther = new List<Other>(); 
+3

「它不喜歡它」 - 這是什麼意思?什麼錯誤信息?什麼意見? 'Charge.Add'需要一個'object',但'iGeneric.Add'需要'T'。這不能編譯。底部代碼塊(您初始化各種列表的位置)與您的問題有什麼關係? –

+0

我改變了它,把它與我正在做的內聯聯繫起來...做了嘗試列表T但我沒有正確的語法/命令。在底部的塊是3我想通過接口使用的列表....接口應該能夠採取我通過的任何列表 – Ggalla1779

+1

我仍然不知道「它不喜歡它」意味着*特別*。另外,我不確定你在問什麼,也不知道你在努力達到什麼目的。請嘗試澄清您的問題。例如,最後,你寫道:「理想情況下,我想在定義列表時設置每個列表和類,即」但是下面的代碼塊(列表初始化)看起來很好,所以有什麼問題? –

回答

1

如果我正確理解你的問題,你可以用泛型來做到這一點。使用像這樣的東西:

public interface IGenericManager<T> 
{ 
    void Add(T obj); 
    void Delete(T obj); 
    void Update(T obj); 
    T View(T obj); 
} 

public class Person 
{ 
    public string Name { get; set; } 
} 

public class PersonManager : IGenericManager<Person> 
{ 
    public void Add(Person obj) 
    { 
     // TODO: Implement 
    } 

    public void Delete(Person obj) 
    { 
     // TODO: Implement 
    } 

    public void Update(Person obj) 
    { 
     // TODO: Implement 
    } 

    public Person View(Person obj) 
    { 
     // TODO: Implement 
     return null; 
    } 
} 
+0

工作治療...謝謝你的清晰度 – Ggalla1779