log4net代码学习:Type 转换 (一)
在一种Type能否转换成另一种Type,一种方法或者最后的方法:获得目标类型的Parse方法,并执行:
- 采用反射获得Parse的MethodInfo
- 调用MethodInfo的Invoke方法
- 当然在最初阶段可以用 Type.IsAssignableFrom
通过类名(string)实例化类:
- 如果能获得其相关类型的Assembly则获得,或者调用当前执行方法的方法的Assembly: Assembly.GetCallingAssembly()
- 如果此时的Assembly不能获得此类的Type,获得当前应用程序域中加载的所有Assembly
- 从这些Assembly中寻找, 最终使用的是Assembly的GetType方法
- 如果最终能获得则执行Activator.CreateInstance()
Type转换的实现,简单类图
-
OptionConverter负责给出Type实例,然后转换成目标类型的实例。它在引用ConverterRegistry来获得Converter来转换。
-
ConverterRegister主要负责存储Type转换实例converters。提供获得converter的方法。这里有个关键的方法:在初始阶段知道有相关的converters,可以在类中直接添,如果已完成的情况下,如何在不修改原有的代码或者ConverterRegister的情况下加入并能存储新的converter实例?
-
这里就要使用Attribute,创建相关的Attribute类,在创建相关的Convert类时候加入此属性,就可以让ConverterRegistry在获得Type converter时候自动添加。
private static object GetConverterFromAttribute(Type destinationType) { // Look for an attribute on the destination type object[] attributes = destinationType.GetCustomAttributes(typeof(TypeConverterAttribute), true); if (attributes != null && attributes.Length > 0) { TypeConverterAttribute tcAttr = attributes[0] as TypeConverterAttribute; if (tcAttr != null) { Type converterType = SystemInfo.GetTypeFromString(destinationType, tcAttr.ConverterTypeName, false, true); return CreateConverterInstance(converterType); } } // Not found converter using attributes return null; }