有一个问题,在我的应用中垃圾回收了我的listview源对象。我有一个选项卡式页面,默认内容页面具有工作列表视图,并且使用几乎相同的代码,第二个内容页面具有另一个列表视图,但未显示对象。反正有什么办法防止它们被垃圾收集?
这是我后面的代码:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using MIApp.Classes;
using Xamarin.Forms;
namespace MIApp
{
public partial class VideosListPage : ContentPage
{
public VideosListPage()
{
InitializeComponent();
}
protected async override void OnAppearing()
{
base.OnAppearing();
HttpClient client = new HttpClient();
string url = "https://example.net/api/Videos/GetVideos";
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
string res = "";
using (HttpContent content = response.Content)
{
Task<string> result = content.ReadAsStringAsync();
res = result.Result;
var VideosList = Videos.VideosItems.FromJson(res);
VideosListView.ItemsSource = VideosList;
}
}
else
{
await DisplayAlert("Connection Error", "Please Connect to the internet and try again", "Ok");
}
}
}
}
因此,我正在从API中获取JSON字符串,该API将数据库中的条目转换为对象的JSON数组。然后,当我在其中构造和反序列化对象的类中声明VideosList var时,将其转换为对象列表:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace MIApp.Classes
{
public class Videos
{
public partial class VideosItems
{
[JsonProperty("$id")]
public long Id { get; set; }
[JsonProperty("intVideoID")]
public string IntVideoId { get; set; }
[JsonProperty("strVideoTitle")]
public string StrVideoTitle { get; set; }
[JsonProperty("strVideoURL")]
public string StrVideoURL { get; set; }
[JsonProperty("strVideoPhotoUrl")]
public string StrVideoPhotoUrl { get; set; }
}
public partial class VideosItems
{
public static List<VideosItems> FromJson(string json)
{
return JsonConvert.DeserializeObject<List<VideosItems>>(json);
}
}
}
}
仅供参考,当逐行调试时,当我将鼠标悬停在var视频列表上时,它会扩展并具有正确的对象计数,但是由于对象已被垃圾回收而无法找到资源。
谢谢, 瑞安
答案 0 :(得分:0)
使VideosList成为全局变量,其范围限于
using (HttpContent content = response.Content)
{
Task<string> result = content.ReadAsStringAsync();
res = result.Result;
var VideosList = Videos.VideosItems.FromJson(res);
VideosListView.ItemsSource = VideosList;
}
仅使用using块,因此,一旦编译器退出该块,VideoList变量就会被垃圾回收。如果您在类级别上声明,则不会发生。