[英]Passing property as parameter in method
I know the title could probably be a bit more descriptive/better phrased, but it was the best I could come up with.我知道标题可能更具描述性/措辞更好,但这是我能想到的最好的。
Currently I have a class with a lot of methods looking like the ones below:目前我有一个 class 有很多方法,如下所示:
private static void UpdateArtists()
{
artists.Clear();
foreach (AudioInfo entry in library_entries)
{
artists.Add(entry.Artist, entry);
}
}
private static void UpdateAlbums()
{
albums.Clear();
foreach (AudioInfo entry in library_entries)
{
albums.Add(entry.Album, entry);
}
}
private static void UpdateGenres()
{
genres.Clear();
foreach (AudioInfo entry in library_entries)
{
genres.Add(entry.Genre, entry);
}
}
private static void UpdateYears()
{
years.Clear();
foreach (AudioInfo entry in library_entries)
{
years.Add(entry.Year, entry);
}
}
Needless to say, writing dozens of these is very tiresome.不用说,写几十个是很累的。 So I was wondering if it's possible to simplify it and make a method something like this:所以我想知道是否可以简化它并制作一个类似这样的方法:
private static void Update(Dictionary<string, AudioInfo> dictionary, AudioInfo.Property property)
{
dictionary.Clear();
foreach (AudioInfo entry in library_entries)
{
dictionary.Add(entry.property, entry);
}
//Where "property" is a property in the AudioInfo-class.
}
Is that doable, and if it is;那是否可行,如果可行; how?如何?
Thanks!谢谢!
It seems like you have some design errors in your class if you need to do such things.如果您需要执行此类操作,您的 class 中似乎存在一些设计错误。 nevertheless, the solution is:然而,解决方案是:
private static void Update(Dictionary<string, AudioInfo> dictionary, Func<AudioInfo, string> func)
{
dictionary.Clear();
foreach (AudioInfo entry in library_entries)
{
dictionary.Add(func(entry), entry);
}
}
And the usage is:用法是:
Update(years, x => x.Year);
Also you can use easier way, instead of call any methods you can just write:您也可以使用更简单的方法,而不是调用您可以编写的任何方法:
years = library_entries.ToDictionary(x => x.Year, x => x);
If you have not any events, linked with your dictionary.如果您没有任何事件,请与您的字典链接。
And one more thing to go - you can't add different elements with the same keys to dictionary. go 还有一件事-您不能将具有相同键的不同元素添加到字典中。 In your case it seems like you have different AudioInfo
objects with the same Year
, Genre
etc.在您的情况下,您似乎有不同的AudioInfo
对象具有相同的Year
, Genre
etc。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.