gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:11:03 25 4
gpt4 key购买 nike

我以前从未这样做过,虽然我想不出它会中断的具体原因,但我想验证使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com