首先,您可能应该重新考虑您的方法。但是,如果所有其他方法都失败了,您可以通过以下方式将属性添加到密封类:
using System;
using System.Runtime.CompilerServices;
namespace DataCellExtender
{
#region sample 3rd party class
public class DataCell
{
public int Field1;
public int Field2;
}
#endregion
public static class DataCellExtension
{
//ConditionalWeakTable is available in .NET 4.0+
//if you use an older .NET, you have to create your own CWT implementation (good luck with that!)
static readonly ConditionalWeakTable<DataCell, IntObject> Flags = new ConditionalWeakTable<DataCell, IntObject>();
public static int GetFlags(this DataCell dataCell) { return Flags.GetOrCreateValue(dataCell).Value; }
public static void SetFlags(this DataCell dataCell, int newFlags) { Flags.GetOrCreateValue(dataCell).Value = newFlags; }
class IntObject
{
public int Value;
}
}
class Program
{
static void Main(string[] args)
{
var dc = new DataCell();
dc.SetFlags(42);
var flags = dc.GetFlags();
Console.WriteLine(flags);
}
}
}
请不要这样做,除非你真的必须这样做。如果您跳过了一种更简洁的解决方案,而转而采用这种略显老套的方法,那么此代码的未来维护者可能会对您有一些强烈的看法。