How can I get fields used in a method (.NET)?

前端 未结 5 1022
名媛妹妹
名媛妹妹 2020-12-16 06:45

In .NET, using reflection how can I get class variables that are used in a method?

Ex:

class A
{
    UltraClass B = new(..);
    SupaClass C = new(..         


        
5条回答
  •  北海茫月
    2020-12-16 07:22

    @Ian G: I have compiled the list from ECMA 335 and found out that I can use

    List mis = 
        myObject.GetType().GetMethods().Where((MethodInfo mi) =>
            {
                mi.GetCustomAttributes(typeof(MyAttribute), true).Length > 0;
            }
        ).ToList();
    foreach(MethodInfo mi in mis)
    {
        List lst = ReflectionHelper.ReadIL(mi);
        ... find useful opcode
        FieldInfo fi = mi.Module.ResolveField((int)usefulOpcode.Argument);
        object o = fi.GetValue(myObject);
        ...
    }
    

    And the opcode length list is here, if anyone needs it:

    Dictionary operandSizes
    = new Dictionary()
    {
        {OperandType.InlineBrTarget, 4},
        {OperandType.InlineField, 4},
        {OperandType.InlineI, 4},
        {OperandType.InlineI8,8},
        {OperandType.InlineMethod,4},
        {OperandType.InlineNone,0},
        {OperandType.InlineR,8},
        {OperandType.InlineSig,4},
        {OperandType.InlineString,4},
        {OperandType.InlineSwitch,4},
        {OperandType.InlineTok,4},
        {OperandType.InlineType,4},
        {OperandType.InlineVar,2},
        {OperandType.ShortInlineBrTarget,1},
        {OperandType.ShortInlineI,1},
        {OperandType.ShortInlineR,4},
        {OperandType.ShortInlineVar,1}
    };
    

提交回复
热议问题