小编tg7*_*g73的帖子

这个闭包组合行为是C#编译器的错误吗?

我正在调查一些奇怪的对象生命周期问题,并遇到了C#编译器的这种非常令人费解的行为:

考虑以下测试类:

class Test
{
    delegate Stream CreateStream();

    CreateStream TestMethod( IEnumerable<string> data )
    {
        string file = "dummy.txt";
        var hashSet = new HashSet<string>();

        var count = data.Count( s => hashSet.Add( s ) );

        CreateStream createStream = () => File.OpenRead( file );

        return createStream;
    }
}
Run Code Online (Sandbox Code Playgroud)

编译器生成以下内容:

internal class Test
{
  public Test()
  {
    base..ctor();
  }

  private Test.CreateStream TestMethod(IEnumerable<string> data)
  {
    Test.<>c__DisplayClass1_0 cDisplayClass10 = new Test.<>c__DisplayClass1_0();
    cDisplayClass10.file = "dummy.txt";
    cDisplayClass10.hashSet = new HashSet<string>();
    Enumerable.Count<string>(data, new Func<string, bool>((object) cDisplayClass10, __methodptr(<TestMethod>b__0)));
    return new …
Run Code Online (Sandbox Code Playgroud)

c# lambda closures .net-4.6

16
推荐指数
2
解决办法
544
查看次数

为什么C#struct方法不能返回对字段的引用,但非成员方法可以?

这是struct尝试将readonly ref返回到struct的实例字段的实例方法的示例:

struct Foo
{
    internal int _x;

    public ref readonly int MemberGetX() => ref _x;
    //                                          ^^^
    // Error CS8170: Struct members cannot return 'this' or other instance members by reference
}
Run Code Online (Sandbox Code Playgroud)

这会产生错误CS8170 Struct成员无法通过引用返回'this'或其他实例成员.但是,使用扩展方法执行相同操作不会产生错误:

static class FooExtensions
{
    public static ref readonly int ExtensionGetX( this in Foo foo )
    {
        return ref foo._x;
    }
}
Run Code Online (Sandbox Code Playgroud)

相关问题的答案 为什么C#结构不能返回对其成员字段的引用?讨论为什么语言不允许第一种情形的原因,但鉴于这些原因,为什么第二种情况下这不是很清楚,我允许的.


更新:

这是一个不使用的完整示例,readonly还显示了非扩展方法,并演示了用法:

struct Foo
{
    internal int _x;

    // Can't compile, error CS8170
    // public ref …
Run Code Online (Sandbox Code Playgroud)

c#

15
推荐指数
1
解决办法
643
查看次数

标签 统计

c# ×2

.net-4.6 ×1

closures ×1

lambda ×1