在我的应用程序中,我想从 WCF 服务(作为 Windows 服务托管)返回一组对象,以填充 WPF 应用程序中的 DataGrid。集合中的对象数量从一到几百不等,具体取决于调用的方法。
我很好奇处理从服务返回大型集合的“最佳”方法是什么。
这些是我看到的建议选项:
yield关键字做一些事情,但这超出了我的头脑,我无法遵循它。:-/完成这项任务的最佳方法是什么,为什么?
下面是一个示例代码.我的循环只循环一次,即使其中有三个项目.items[0].Duration只返回添加的顶级项目.它没有循环遍历集合.
有任何想法吗?
public class DurationModel
{
public string Duration { get; set; }
public IEnumerable<List<DurationModel>> GetDurationItems()
{
List<DurationModel> durationItems = new List<DurationModel>();
durationItems.Add(new DurationModel()
{
Duration = "1 Day"
});
durationItems.Add(new DurationModel()
{
Duration = "1 Week"
});
durationItems.Add(new DurationModel()
{
Duration = "1 Month"
});
yield return durationItems;
}
}
public class MyForm
{
private ObservableCollection<string> _durationItems = new ObservableCollection<string>();
private IEnumerable<List<DurationModel>> _durationModel = new DurationModel().GetDurationItems();
public MyForm()
{
GetData();
}
private void GetData()
{
foreach (var …Run Code Online (Sandbox Code Playgroud) 问题
当我尝试在async方法中调用我的“ normal”方法时,它将从Debugger 1中被忽略。
这是我的异步方法
internal async static Task<DefinitionsModel> DeserializeAsync(this string path)
{
var model = new DefinitionsModel();
var content = await File.ReadAllTextAsync(path);
model.Pages = content.GetPages();
return model;
}
Run Code Online (Sandbox Code Playgroud)
这是我的“正常”方法
private static IEnumerable<PageModel> GetPages(this string content)
{
var level = 0;
var value = nameof(PageModel.Page).GetDElement<PageModel>();
var start_with_line = $"{level} {value} ";
var end_with_line = string.Concat(Enumerable.Repeat(Environment.NewLine, 2));
var expression = $@"\b{start_with_line}\S * {end_with_line}\b";
var matches = content.GetPagesFromContent(expression);
yield return new PageModel();
}
Run Code Online (Sandbox Code Playgroud)
帮助图片
我知道收益率是多少,但我无法理解为什么要使用它,是不是因为它为我节省了一行列表声明?
它必须是更多的东西.
什么是最好用它?
*我问过在哪里以及为什么要使用它,它的优点是什么,而不是它的优点.
我发现了一件有趣的事情.c#,.NET 4.0.我有一个代表IDisposable接口的类.在上面提到的类中我有一个函数,返回IEnumerable并返回yield.在调用时,controll跳过该函数.请勿介入.示例:
class Program
{
static void Main(string[] args)
{
using (DispClass d = new DispClass())
{
d.Get2();
d.Get1();
}
}
}
public class DispClass: IDisposable
{
public DispClass()
{
Console.WriteLine("Constructor");
}
public void Dispose()
{
Console.WriteLine("Dispose");
}
public int Get1()
{
Console.WriteLine("Getting one");
return 1;
}
public IEnumerable<int> Get2()
{
Console.WriteLine("Getting 1");
yield return 1;
Console.WriteLine("Getting 2");
yield return 2;
}
}
Run Code Online (Sandbox Code Playgroud)
输出:"构造函数""获取一个""处理"
"获得1","获得2"在哪里?如果没有收益率返回并返回本地列表,我可以看到这些......
请解释!