作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 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/
我是一名优秀的程序员,十分优秀!