小编Mat*_*wan的帖子

C#Foreach优化与反射

基本上,这个代码段是:

// Get these once, create list, re-use same list
var prodType = products.GetType();
var fieldInfList = prodType.GetFields();
var propInfList = prodType.GetProperties();

foreach (var p in products)
{
    foreach (var fieldInf in fieldInfList)
    {
        fieldInf.SetValue(this, fieldInf.GetValue(p));
    }
    foreach (var propInf in propInfList)
    {
        propInf.SetValue(this, propInf.GetValue(p));
    }
}
Run Code Online (Sandbox Code Playgroud)

比这更快:

foreach (var p in products)
{
    foreach (var fieldInf in products.GetType().GetFields())
    {
        fieldInf.SetValue(this, fieldInf.GetValue(p));
    }
    foreach (var propInf in products.GetType().GetProperties())
    {
        propInf.SetValue(this, propInf.GetValue(p));
    }
}
Run Code Online (Sandbox Code Playgroud)

...?

我的想法是,对于第二个块,每个循环将执行再次检查对象的工作,而第一个将具有将在每个循环中持续存在的列表.

与线路类似

var prodType = products.GetType(); …
Run Code Online (Sandbox Code Playgroud)

.net c# optimization

3
推荐指数
1
解决办法
178
查看次数

标签 统计

.net ×1

c# ×1

optimization ×1