使用泛型类型约束的方法,如何使用?

时间:2014-08-03 08:17:12

标签: c# asp.net windows-phone-8

我正在使用以下方法从IsolatedStorageSettings"

保存和获取数据

然后让我们提供两种方法Save / Load:

public static void SaveAudioList(string AudioListKey, IList<SongPlay> audioList)
{
    IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
    if (settings.Contains(AudioListKey)) settings[AudioListKey] = audioList;
    else settings.Add(AudioListKey, audioList);
}

我保存了这样的数据:

SongPlay songdetail = new SongPlay();
//songdetail.Album = "1";
//songdetail.Artist = "Love Guru";
songdetail.SongName = (string)track["name"];
songdetail.Url =(string)track["url"];

AudioTracks.Add(songdetail);
//StorageUtility.AddOrUpdateValue("tracklist", AudioTracks);
ClassLib.Class1.SaveAudioList("id", AudioTracks);

从get value我写下面的方法:

public static void LoadAudioList<T>(string AudioListKey, ref T target) where T : IList<SongPlay>
{
    IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
    if (!settings.Contains(AudioListKey)) throw new NotImplementedException(); // do something - list doesnt exist
    target = (T)settings[AudioListKey];
}

现在我想用这个:

LoadAudioList

我怎么称呼它?

1 个答案:

答案 0 :(得分:0)

为什么LoadAudioList是通用方法?
它是一个空函数,想要执行IList<SongPlay>的简单赋值。

为什么不实现这样的事情:

public static IList<SongPlay> LoadAudioList(string AudioListKey)
{
    IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
    if (!settings.Contains(AudioListKey)) throw new NotImplementedException(); // do something - list doesnt exist
    return settings[AudioListKey] as IList<SongPlay>;
}

如果你想让它无效:

public static void LoadAudioList(string AudioListKey, ref IList<SongPlay> target)
{
    IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
    if (!settings.Contains(AudioListKey)) throw new NotImplementedException(); // do something - list doesnt exist
    target = settings[AudioListKey] as IList<SongPlay>;
}