我正在调查一些奇怪的对象生命周期问题,并遇到了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) 这是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)