有没有办法将不同的存储库传递给通用方法并让它们使用方法中生成的变量?

Is there a way to pass different repositories into a generic method and have them use variables generated within the method?

在我当前的 class 中,我有以下代码块

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;

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

我想将它们粘贴到一个通用方法中,该方法只是 returns 一个名称字符串,但我不知道如何传入一个 repo 并让它使用特定方法来获取主题或国家。

这可能吗?还是麻烦多于它的价值?

当您通过委托访问存储库的部分时,这是可能的。此外,为了访问 Name 属性,你的 country 和你的 subject 变量应该有一个共同的基类型(我只是假设一个接口 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。我还通过使用 null 合并运算符简化了最后一行(你的问题有重构标签)。

用法是

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