我做了一个C++
来模拟[StructLayout(LayoutKind.Explicit)]
class Class {
[FieldOffset(0)] public byte Whole;
[FieldOffset(0)] [BitsAspect(0,0)] public byte Bit0;
[FieldOffset(0)] [BitsAspect(1,1)] public byte Bit1;
}
位字段,这种方式应用了这种方式:
class
效果很好,但只适用于struct
es。在[StructLayout(LayoutKind.Explicit)]
struct Struct {
[FieldOffset(0)] public byte Whole;
[FieldOffset(0)] [BitsAspect(0,0)] public byte Bit0;
[FieldOffset(0)] [BitsAspect(0,1)] public byte Bit1;
}
s它只是不起作用:
[TestMethod]
public void BitOperations_Test() {
var c = new Class();
c.Bit1 = 1;
Assert.AreEqual(2, c.Whole);
Assert.AreEqual(1, c.Bit1);
// all assertions pass to this point.
var s = new Struct();
s.Bit1 = 1;
Assert.AreEqual(2, s.Whole); // fails: s.Whole is 1 :-(
Assert.AreEqual(1, s.Bit1);
}
以下是测试:
[Serializable]
[MulticastAttributeUsage(MulticastTargets.Property | MulticastTargets.Field)]
public class BitsAspect : LocationInterceptionAspect {
private ulong _mask;
private Type _type;
public int BitOffset { get; private set; }
public int BitsCount { get; private set; }
public BitsAspect(int bitOffset, int bitsCount) {
BitOffset = bitOffset;
BitsCount = bitsCount;
}
public override void CompileTimeInitialize(LocationInfo targetLocation, AspectInfo aspectInfo) {
_type = targetLocation.LocationType;
if (_type.IsEnum) _type = _type.GetEnumUnderlyingType();
ulong mask = ((ulong) 1 << BitsCount) - 1;
_mask = mask << BitOffset;
base.CompileTimeInitialize(targetLocation, aspectInfo);
}
public override void OnGetValue(LocationInterceptionArgs args) {
var @this = args.Instance;
var oldValue = Convert.ToUInt64(args.Binding.GetValue(ref @this, Arguments.Empty));
var value = (oldValue & _mask) >> BitOffset;
var converted = Convert.ChangeType(value, _type);
args.Value = converted;
}
public override void OnSetValue(LocationInterceptionArgs args) {
var @this = args.Instance;
var newValue = Convert.ToUInt64(args.Value);
var oldValue = Convert.ToUInt64(args.Binding.GetValue(ref @this, Arguments.Empty));
var value = (oldValue & ~_mask) | (newValue << BitOffset);
var converted = Convert.ChangeType(value, _type);
args.SetNewValue(converted);
}
}
方面:
struct
我可以用值类型.InRequestScope()
来实现这一点吗?
答案 0 :(得分:1)
结构上的LocationInterceptionAspect在这里没有任何问题。
Bit1的声明对于Class有点不同:
[FieldOffset(0)] [BitsAspect(1,1)] public byte Bit1;
和结构:
[FieldOffset(0)] [BitsAspect(0,1)] public byte Bit1;
我敢打赌它会有所不同。
注意可变值类型,它们可以是pure evil。