gpt4 book ai didi

c# - 合并泛型方法

转载 作者:行者123 更新时间:2023-11-30 22:38:39 26 4
gpt4 key购买 nike

我是 C# 的新手,我有以下 3 种方法。这些方法允许调用者通过在给定方法上指定 lambda 表达式来检索表的不同属性。但是,我觉得专家会进一步将它们组合成一个通用方法。如果可行,请告诉我具体方法。

private KeyValuePair<T, int> GetHeaderProperty<T>(Func<Header, T> Property, 
Source ds)
{
Func<Source, Header> GetValue =
a => Books.Where(str => str.BookId == a.DiscardBookId)
.First().Header;
return new KeyValuePair<T,int>(Property(GetValue(ds)), 0);
}

private KeyValuePair<T, int> GetBookProperty<T>(Func<Book, T> Property,
Source ds)
{
Func<Source, Book> GetValue =
a => Books.Where(str => str.BookId == a.DiscardBookId).First();

return new KeyValuePair<T, int>(Property(GetValue(ds)), 0);
}

private KeyValuePair<T, int> GetFleetProperty<T>(Func<Fleet, T> Property,
Source ds)
{
Func<Source,Fleet> GetValue =
a => Books.Where(str => str.BookId == a.DiscardBookId).First()
.Header.Fleet;

return new KeyValuePair<T,int>(Property(GetValue(ds)), 0);
}

最佳答案

我认为以下将等同于连续调用所有三个方法并将结果添加到列表中:

private IEnumerable<KeyValuePair<T, int>> GetFleetProperty<T>(
Func<Book, T> PropertyBook,
Func<Header, T> PropertyHeader,
Func<Fleet, T> PropertyFleet,
Source ds)
{
Func<Source,Fleet> GetValue =
a => Books.Where(str => str.BookId == a.DiscardBookId).First();

var book = GetValue(ds);
var result = new List<KeyValuePair<T, int>>();
result.Add(new KeyValuePair<T, int>(PropertyBook(book), 0);
result.Add(new KeyValuePair<T, int>(PropertyHeader(book.Header), 0);
result.Add(new KeyValuePair<T, int>(PropertyFleet(book.Header.Fleet), 0);
return result;
}

更新:
您还可以创建这样的方法:

private KeyValuePair<T, int> GetProperty<T, TProperty>(
Func<TProperty, T> Property,
Func<Book, TProperty> GetProperty,
Source ds)
{
Func<Source, Header> GetValue =
a => Books.Where(str => str.BookId == a.DiscardBookId)
.First();
var book = GetValue(ds);
return new KeyValuePair<T,int>(Property(GetProperty(book)), 0);
}

你可以这样称呼标题:

GetProperty(xyz, b => b.Header, ds);

对于 Book,您可以这样调用它:

GetProperty(xyz, b => b, ds);

对于舰队,您可以这样调用它:

GetProperty(xyz, b => b.Header.Fleet, ds);

关于c# - 合并泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6018017/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com