簡體   English   中英

在 C# 中使用泛型類型的多種類型列表

[英]List of multiple types using generic types in c#

我創建了一個可以保留兩種類型列表的類:TPersonA 和 TPersonB(它們在一個屬性上有所不同)。 工作完美,但是當我想編輯特定字段時就會出現問題,因為它們因類型而異。

public class Repository<T> : IRepository<T>
        where T : class, IEntity<int>, IPerson
    {
        protected static List<T> _dataBase = new List<T>();
        ...
        public void Edit(T entity)
        {
            var toEdit = _dataBase.FirstOrDefault(x => x.Id == entity.Id);
            toEdit.Id = entity.Id;
            toEdit.FirstName = entity.FirstName;
            toEdit.LastName = entity.FirstName;
            toEdit.DateOfBirth = entity.DateOfBirth;
            toEdit.Section = entity.Section;

            switch (entity)
            {
                case TPersonA a:
                    toEdit.Specialization = entity.Specialization;
                    break;
                case TPersonB b:
                    toEdit.AIndex = entity.AIndex;
                    break;
            }
        }
    }

當前代碼不起作用,編譯器不知道 Specialization 和 AIndex 是什么,這是可以理解的,因為 TPersonA 和 B 的層次結構低於基本類 TPerson。 但是當我將 IPersonA 和 IPersonB 添加到約束時,我在 Main 中的代碼將不再起作用。

IRepository<TPerson> repository = new Repository<TPerson>();

這也是可以理解的。 因為 TPerson 的層級較高,無法轉換為 A 或 B。我該如何解決? 我試圖通過創建輔助類來繞過它,該類將處理泛型類型無法完成的所有操作,但隨后我無法訪問 _dataBase。

您可以將entity為同一類:

switch (entity)
{
    case TPersonA a when toEdit is TPersonA castedEntity:
        castedEntity.Specialization = a.Specialization;
        break;
    case TPersonB b when toEdit is TPersonB castedEntity:
        castedEntity.AIndex = b.AIndex;
        break;
}

但我不建議這樣做。 最好為TPersonATPersonB設置兩個不同的存儲庫,即使它們的對象保存在同一個表中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM