c# - 在 LINQ 语句中的调用中使用 out 变量是否安全?

标签 c# linq

我以前从未这样做过,虽然我想不出它会中断的具体原因,但我想验证使用 out 变量是否有效,如下所示:

void Main()
{
    var types = new [] { typeof(A), typeof(B) };
    bool b = false;
    var q = from type in types
            from property in type.GetProperties()
            let propertyName = GetName(property, out b)
            select new {
                TypeName = type.Name,
                PropertyName = propertyName,
                PropertyType = property.PropertyType.Name,
                IsNullable = b
            };
    q.Dump();
}

private string GetName(PropertyInfo property, out bool isNullable)
{
    string typeName;
    isNullable = false;
    var type = property.PropertyType;
    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
    {
        isNullable = true;
        typeName = type.GetGenericArguments().First().Name;
    }
    else
    {
        typeName = property.Name;
    }
    return typeName;
}

最佳答案

这会奏效 - 前提是您实际对查询进行了全面评估。

但是,这种行为会很奇怪,我会极力避免这种行为。由于 out 参数直接在查询中使用,因此这里的行为将相当正常(前提是您不对此执行任何其他操作),但这是特定于此用例的,而不是使用 out 的一般“规则”与 LINQ 混合。

问题是 LINQ 的延迟执行会导致 out 参数被设置,但只有当您使用结果可枚举时才会设置,而不是在您声明它时。这可能会导致非常意外的行为,并导致难以维护和理解软件。

我个人只会编写一个单独的方法,并使用它来让您的查询编写为:

var q = from type in types 
        from property in type.GetProperties() 
        let propertyName = GetName(property)
        let nullable = GetIsNullable(property)
        // ...

这样就清楚多了,也不容易出错和错误。它还将与并行化(即:PLINQ via .AsParallel())和其他技术一起工作,如果有人稍后试图改变它的话。

关于c# - 在 LINQ 语句中的调用中使用 out 变量是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10542610/

相关文章:

c# - 使用 ALL 的 LINQ 查询

c# - 在 for each 循环中使用 DisplayFor

c# - 是否可以在自定义 WCF 服务行为中创建 TransactionScope? (异步、等待、TransactionScopeAsyncFlowOption.Enabled)

C# 'Unassigned local variable' ?

c# - 在结构上使用 "new"是在堆还是堆栈上分配它?

c# - Linq 从 Dictionary 值匹配中返回WhereEnumerableIterator?

c# - 我如何从另一个可枚举的 c# 中插入一个可枚举的

c# - 使用 AutoMapper 覆盖已解析的属性类型

c# - 当我只需要计数而不读取 Document-Db 数据库中的所有文档时,如何使用 Linq 构建 IQueryable 查询?

c# - unmanaged.dll.manifest 文件有什么用途?