gpt4 book ai didi

dynamic - 为什么 C# 编译器在 'use of an unassigned variable' 和动态之前声明 'yield return'?

转载 作者:行者123 更新时间:2023-12-04 21:50:20 24 4
gpt4 key购买 nike

编译器提示 resultingThing在被分配给下面的代码之前正在使用。

private IEnumerable<IThing> FindThings(dynamic spec)
{
if (spec == null)
yield break;

IThing resultingThing;
if (spec.Something > 0 && dictionary.TryGetValue(spec.Something, out resultingThing))
yield return resultingThing;
else
// ...
}

为什么它声称这一点?

我尝试了不同版本的方法,其中没有 产量用法(例如,只是 return IEnumerable<IThing> )但使用 动态参数,并且我尝试了一个版本的方法,其中 动态没有传入(即我们在以前版本的 C# 中所做的)。这些编译。

最佳答案

我似乎是一个编译器错误(或限制,如果您愿意)。

我将最小的失败案例减少到:

static private IThing FindThings(dynamic spec)
{
IThing resultingThing;
if ((null!=spec) && dictionary.TryGetValue(spec, out resultingThing))
return resultingThing;
return null;
}

这给出了相同的编译器诊断,不涉及动态成员查找,也不涉及迭代器块。

作为引用,单声道编译器不会因此而绊倒:
using System;
using System.Collections.Generic;

public static class X
{
public interface IThing { }

private static readonly IDictionary<string, IThing> dictionary = new Dictionary<string, IThing>();

static private IThing FindThings(dynamic spec)
{
IThing resultingThing;
if ((null!=spec) && dictionary.TryGetValue(spec, out resultingThing))
return resultingThing;
return null;
}

public static void Main(string[] s)
{

}
}

编译:
dmcs -v -warnaserror -warn:4 t.cs

没有警告

关于dynamic - 为什么 C# 编译器在 'use of an unassigned variable' 和动态之前声明 'yield return'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6051711/

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