接口中的通用列表

时间:2017-01-11 16:15:51

标签: c# list interface

创建一个界面,我要求它能够处理不同的列表类型,我应该使用什么?

使用我在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.");
            }
        }

理想情况下,我想在定义List时设置每个List和类。

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

1 个答案:

答案 0 :(得分: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;
    }
}