为了账号安全,请及时绑定邮箱和手机立即绑定

C# 电话簿项目的通用方法

C# 电话簿项目的通用方法

PHP
慕运维8079593 2024-01-20 16:14:08
我正在尝试制作电话簿项目,其中我从 bin 文件写入/读取数据,我在域类库中有两个类,用户和联系人,现在我想在 FileManager 类中创建私有通用函数,添加/编辑/删除和获取它将为联系人和用户找到/工作,我如何知道private T Get<T>(int id) where T : class函数中给出的是哪种类型?使其适用于两种类型如何正确完成这些功能呢?
查看完整描述

1 回答

?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

我认为您应该分别为 User 和 Contact 类创建一个通用接口及其实现。如果出现一个新类,例如 Employee - 您将对此接口进行新的实现,而无需对 User 和 Contact 类进行任何更改。如果源不是二进制文件,而是数据库 - 那么该接口的单独实现。


如下:


interface IManager<TEntity> where TEntity : class

    {

        IList<TEntity> GetAll();

        TEntity GetById(int id);

        void Add(TEntity entity);

        void Update(TEntity entity);

        void Remove(int id);

        int GenerateContactId();

        IList<TEntity> Search(Func<TEntity, bool> p);

    }


    class BinaryContactManager : IManager<Contact>

    {

        public void Add(Contact entity)

        {

            throw new NotImplementedException();

        }


        public int GenerateContactId()

        {

            throw new NotImplementedException();

        }


        public IList<Contact> GetAll()

        {

            throw new NotImplementedException();

        }


        public Contact GetById(int id)

        {

            throw new NotImplementedException();

        }


        public void Remove(int id)

        {

            throw new NotImplementedException();

        }


        public IList<Contact> Search(Func<Contact, bool> p)

        {

            throw new NotImplementedException();

        }


        public void Update(Contact entity)

        {

            throw new NotImplementedException();

        }

    }


    class BinaryUserManager : IManager<User>

    {

        public void Add(User entity)

        {

            throw new NotImplementedException();

        }


        public int GenerateContactId()

        {

            throw new NotImplementedException();

        }


        public IList<User> GetAll()

        {

            throw new NotImplementedException();

        }


        public User GetById(int id)

        {

            throw new NotImplementedException();

        }


        public void Remove(int id)

        {

            throw new NotImplementedException();

        }


        public IList<User> Search(Func<User, bool> p)

        {

            throw new NotImplementedException();

        }


        public void Update(User entity)

        {

            throw new NotImplementedException();

        }

    }



查看完整回答
反对 回复 2024-01-20
  • 1 回答
  • 0 关注
  • 25 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信