简体   繁体   中英

Generic list in Interface

Am creating an interface and I require it to be able to handle different list types, what should I be using?

Am using classes which I use in Lists of List<Person> , List<Charge> , List<Other>

I did try this interface but its not the right Generic List Type, or type I am using

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

And the charge class inheriting the iGeneric interface

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.");
            }
        }

Ideally I would like to set each List and class when I define the List ie

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

If I understood your question correctly, you can do this with generics. Use something like this:

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM