How to test whether a value is boxed in C# / .NET?

后端 未结 9 1317
终归单人心
终归单人心 2020-12-13 00:32

I\'m looking for a way to write code that tests whether a value is boxed.

My preliminary investigations indicate that .NET goes out of its way to conceal the fact,

9条回答
  •  悲哀的现实
    2020-12-13 01:25

    I'm not sure if this will be relevant to anyone, but since I encountered this post because boxing was actually impacting my very dynamic mapping.

    Sigil proivdes a fantastic UnBoxAny method

    Assuming you have the following:

    public class Report { public decimal Total { get; set; } }

    new Dictionary { { "Total", 5m} }

    So the decimal value is boxed.

    var totalProperty = typeof(Report).GetProperty("Total");
    
    var value = emit.DeclareLocal();
    
    //invoke TryGetValue on dictionary to populate local 'value'*
                                                        //stack: [bool returned-TryGetValue]
    //either Pop() or use in If/Else to consume value **
                                                        //stack: 
    //load the Report instance to the top of the stack 
    //(or create a new Report)
                                                        //stack: [report]
    emit.LoadLocal(value);                              //stack: [report] [object value]
    emit.UnboxAny(totalProperty.PropertyType);          //stack: [report] [decimal value]
    
    //setter has signature "void (this Report, decimal)" 
    //so it consumes two values off the stack and pushes nothing
    
    emit.CallVirtual(totalProperty.SetMethod);          //stack: 
    
    
    

    * invoke TryGetValue

    ** use in If/Else

    提交回复
    热议问题