1. programming 1.1 C#

第一次使用泛型!

2024 年 2 月 9 日

我問ChatGPT:請問這兩段程式碼要怎麼合併比較恰當?

        public List<TodoRecord> GetRecords()
        {
            string filePath = _todoViewModel.RecordFileName;
            if (File.Exists(filePath))
            {
                // Read the file
                string json = File.ReadAllText(filePath);
                try
                {
                    // Deserialize JSON
                    _todoViewModel.todoRecords = JsonSerializer.Deserialize<List<TodoRecord>>(json);
                    return _todoViewModel.todoRecords;
                }
                catch (Exception)
                {
                    throw;
                }

            }
            else
            {
                return _todoViewModel.todoRecords;
            }
        }
        public List<TodoTitle> GetTitles()
        {
            string filePath = _todoViewModel.TitleFileName;
            if (File.Exists(filePath))
            {
                // Read the file
                string json = File.ReadAllText(filePath);
                try
                {
                    // Deserialize JSON
                    _todoViewModel.todoRecords = JsonSerializer.Deserialize<List<TodoRecord>>(json);
                    return _todoViewModel.todoTitles;
                }
                catch (Exception)
                {
                    throw;
                }

            }
            else
            {
                return _todoViewModel.todoTitles;
            }
        }

ChatGPT:這兩段程式碼的目的是讀取不同的檔案,然後反序列化 JSON,最後返回相應的清單。為了合併這兩個方法,你可以將它們的相似邏輯提取出來,並將檔案路徑和返回的清單作為參數傳遞。以下是合併後的程式碼:

public List<T> GetItems<T>(string filePath, List<T> targetList)
{
    if (File.Exists(filePath))
    {
        // Read the file
        string json = File.ReadAllText(filePath);
        try
        {
            // Deserialize JSON
            targetList = JsonSerializer.Deserialize<List<T>>(json);
            return targetList;
        }
        catch (Exception)
        {
            throw;
        }
    }
    else
    {
        return targetList;
    }
}

public List<TodoRecord> GetRecords()
{
    string filePath = _todoViewModel.RecordFileName;
    return GetItems(filePath, _todoViewModel.todoRecords);
}

public List<TodoTitle> GetTitles()
{
    string filePath = _todoViewModel.TitleFileName;
    return GetItems(filePath, _todoViewModel.todoTitles);
}

合併讀取檔案程式 (openai.com)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *