使用反射来确定哪个基类的构造函数被调用 [英] Use reflection to determine which base class constructor is called

查看:239
本文介绍了使用反射来确定哪个基类的构造函数被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上使用反射 DerivedClassB ,我们才能确定类型:
一),它使用的基类构造函数,它接受一个字符串参数
B),它传递的实际价值呢?

 公共类BaseClass的
{
    公众的BaseClass()
    {
    }

    公众的BaseClass(字符串someParameter)
    {
    }
}

公共类DerivedClassA:BaseClass的
{
    公共DerivedClassA()
    {
    }
}

公共类DerivedClassB:BaseClass的
{
    公共DerivedClassB():基地(canWeFindThis)
    {
    }
}
 

解决方案

是。从技术上讲,你可以找出哪些其他的构造函数的调用,如果你读信息ConstructorInfo.GetMethodBody(),但没有像Mono.Cecil能做到一个辅助库,你必须以德丙的IL $ C $从一个字节数组中。

B)对你来说,是的,但一般无。反射只能反映静态数据,而不是运行时动态的状态,所以你不能用它来知道哪些值,除非它被指定为文字被作为参数传递给构造函数,像你这样,在这种情况下,你可以使用同样的技术上面 ConstructorInfo.GetMethodBody()或Mono.Cecil能做到。

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")
    {            
    }
}

解决方案

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.

这篇关于使用反射来确定哪个基类的构造函数被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆