我非常喜欢 C# 语言。我只是在玩,永远不会在生产代码中使用下面的代码。显然编译器被结构的布局所迷惑。但是为什么 Super 类上的字符串仍然可以在运行时读写呢?我会预料到一些内存访问冲突。在运行时检查类型,它说它是 Base 类型,请参阅NoProblem()
函数执行。没有实例化 Super 类。
它怎么能这样运作?
using System;
using System.Runtime.InteropServices;
namespace Fiddle
{
class Program
{
static void Main(string[] args)
{
var b = new Base
{
IntOnBase = 1
};
var overlay = new Overlay();
overlay.Base = b;
var super = overlay.Super;
var intValue = super.IntOnBase;
super.StringOnSuper = "my test string";
var stringValue = super.StringOnSuper;
super.NoProblem();
Expressions.Fiddle();
}
}
[StructLayout(LayoutKind.Explicit)]
public struct Overlay
{
[FieldOffset(0)]
public Super Super;
[FieldOffset(0)]
public Base Base;
}
public class Super : Base
{
public string StringOnSuper { get; set; }
public void NoProblem()
{
Console.WriteLine("You know, I am really a " + this.GetType().Name + " kind of class.");
}
}
public class Base
{
public int IntOnBase { get; set; }
}
}