【问题标题】:Is there a way to pass different repositories into a generic method and have them use variables generated within the method?有没有办法将不同的存储库传递给通用方法并让它们使用方法中生成的变量?
【发布时间】:2021-03-29 09:38:21
【问题描述】:

在我目前的课程中,我有以下代码块

int.TryParse(formDataDictionary["CountryId"], out var countryId);
var country = countryId > 0 ? _countriesRepository.GetCountryById(countryId) : null;
var searchedCountryName = country != null ? country.Name : string.Empty;

int.TryParse(formDataDictionary["SubjectId"], out var subjectId);
var subject = subjectId > 0 ? _subjectsRepository.GetFullSubjectDetailsById(subjectId) : null;
var searchedSubjectName = subject != null ? subject.Name : string.Empty;

如您所见,除了使用不同的存储库外,它们几乎相同。

我想将它们放在一个只返回名称字符串的通用方法中,但我不知道如何传入一个 repo 并让它使用特定方法来获取主题或国家/地区。

这是可能的,还是比它的价值更麻烦?

【问题讨论】:

    标签: c# .net generics .net-core refactoring


    【解决方案1】:

    当您通过委托访问存储库的部分时,这是可能的。此外,为了访问Name 属性,您的countrysubject 变量应该有一个共同的基本类型(我只是假设一个接口IHasName 只有一个属性string Name {get;})。

    public string GetSearchedName<T>(string dictionaryKey, Func<int,T> getValue) where T : IHasName, class
    {
        int.TryParse(formDataDictionary[dictionaryKey], out var id);
        T item = id > 0 ? getValue.Invoke(id) : null;
        return item?.Name ?? string.Empty;
    }
    

    请注意,我使用了class 约束,以便item 可以是null。我还使用空合并运算符简化了最后一行(您的问题有重构标签)。

    用法是

    string seachedCountryName = GetSearchedName("CountryId", (id) => _countriesRepository.GetCountryById(id));
    string searchedSubjectName = GetSearchedName("SubjectId", (id) => _subjectsRepository.GetFullSubjectDetailsById(id));
    

    【讨论】:

    • 这正是我所希望的答案。示例和用法说明,以及顶部的小重构。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 2019-11-20
    • 1970-01-01
    • 2020-04-29
    相关资源
    最近更新 更多