合并通用方法
我是 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);
}
I'm new to C# and I have the following 3 methods. These methods allow the caller to retrieve differents properties of the table by specifying a lambda expression on the given method. However, I have the feeling an expert would combine them even further into a single generic method. If this is possible, please let me know how.
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为以下内容相当于连续调用所有三个方法并将结果添加到列表中:
更新:
您还可以创建这样的方法:
对于 Header,您可以这样称呼它:
对于 Book,您可以这样称呼它:
对于 Fleet,您可以这样称呼它:
I think the following will be equivalent to calling all three methods in a row and adding the results to a list:
UPDATE:
You could also create a method like this:
You would call it like this for Header:
You would call it like this for Book:
You would call it like this for Fleet:
你可以使用这样的东西
You can use some thing like this