我曾经编写过一段代码来为 Task 添加名称。下面的代码似乎做同样的事情,但代码更少。但我想知道,这是否合法。是否准备好生产代码。垃圾回收呢?在代码中移动的类的实例怎么样(因为它没有固定),它在移动时是否仍然有效?如何将此代码进行测试?
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var obj = new object();
obj.Tag("Link some data");
var tag = obj.Tag();
}
}
public static class ObjectExtensions
{
private class Tagger
{
public string Tag { get; set; }
}
[StructLayout(LayoutKind.Explicit)]
private struct Overlay
{
[FieldOffset(0)]
public Tagger Tagger;
[FieldOffset(0)]
public object Instance;
}
public static string Tag(this object obj)
{
var overlay = new Overlay {Instance = obj };
return overlay.Tagger.Tag;
}
public static void Tag(this object obj, string tag)
{
var overlay = new Overlay {Instance = obj };
overlay.Tagger.Tag = tag;
}
}
}