Use reflection to determine which base class const

2019-07-28 17:20发布

Using reflection on the type DerivedClassB can we determine:
a) that it uses the base class ctor that takes a string param
b) the actual value that it passes?

public class BaseClass
{
    public BaseClass()
    {            
    }

    public BaseClass(string someParameter)
    {            
    }
}

public class DerivedClassA : BaseClass
{
    public DerivedClassA()
    {            
    }
}

public class DerivedClassB : BaseClass
{
    public DerivedClassB(): base("canWeFindThis")
    {            
    }
}

2条回答
Explosion°爆炸
2楼-- · 2019-07-28 18:00

a) Yes. Technically, you can find out which other constructors are called, if you read the information from ConstructorInfo.GetMethodBody() but without a helper library like Mono.Cecil, you'd have to decode the IL from a byte array.

b) In your case, yes but generally no. Reflection can only be used to reflect on static data, not runtime dynamic state, so you wouldn't be able to use it to know which values were passed as parameter to a constructor unless it was specified as a literal, like you have, in which case you can use the same technique above with ConstructorInfo.GetMethodBody() or Mono.Cecil.

查看更多
Summer. ? 凉城
3楼-- · 2019-07-28 18:15

As a follow-up to this, I realized that the value being passed to the base class actually gets exposed through a property on the base class.

So for my scenario I just instantiated the type and then interrogated the value of the property to find out what has actually been passed in the constructor. HTH.

查看更多
登录 后发表回答