1.net类型与类型之间进行安全的转换
//获取类型的TypeConverter
Type intType = typeof(int);
Type strType = typeof(string);
TypeConverter typeConverter=TypeDescriptor.GetConverter(strType);
//判断 Type 类型之间是否可以转换
bool isCanConvert=typeConverter.CanConvertTo(intType);//string 类型是否可以转换 int 类型
//转换
string testnum="33";
object convertResult= typeConverter.ConvertTo(testnum,intType);
//最后进行拆箱
int intResult= (int)convertResult;
2.判断一个类型为可空的泛类型,即Nullable<>这种
//获取数据的类型
object a =xxxx;//a不知道是什么类型
//获取a的Type类型
Type sourceType = a.GetType();
//判断Type是否为Nullable<>类型的Type
bool isNullableType=type.IsGenericType && (type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)));
3.PropertyInfo 一般那些对我们有意义
//关注PropertyInfo
PropertyInfo _propertyInfo;
//关注Name
sring _name;
//关注Property的Type
Type _memberType;
//关注Get取值方法
LateBoundPropertyGet _lateBoundPropertyGet;//Emit or Expression 动态代码构造委托
public object GetValue(object source)
{
return _lateBoundPropertyGet(source);
}
//关注Set赋值方法
LateBoundPropertySet _lateBoundPropertySet;//Emit or Expression 创建DynamicMethod
public void SetValue(object destination,object value)
{
_lateBoundPropertySet(destination,value);
}
//如何给关注点赋值
public void Init(PropertyInfo propertyInfo)
{
_propertyInfo = propertyInfo;
_name=_propertyInfo.Name;
_memberType=_propertyInfo.PropertyType;
if(_propertyInfo.GetGetMethod(true)!=null)
_lateBoundPropertyGet= DelegateFactory.CreateGet(propertyInfo);
if(_propertyInfo.GetSetMethod(true)!=null)
_lateBoundPropertySet= DelegateFactory.CreateSet(propertyInfo);
}
//关注Attributes
Type attributeType = typeof(xxxAttribute);
bool inherit = true;//继承
object[] attributes = _propertyInfo.GetCustomAttributes(attributeType,inherit);
object[] attributesNoInherit= _propertyInfo.GetCustomAttributes(attributeType);
4.FieldInfo 一般那些对我们有意义
//关注 FieldInfo
FieldInfo _fieldInfo;
//关注 Name
string _name;
//关注 Field 的Type
Type _memberType;
//关注 Get
LateBoundFieldGet _lateBoundFieldGet;
public object GetValue(object source)
{
return _lateBoundFieldGet(source);
}
//关注 Set
LateBoundFieldSet _lateBoundFieldSet;
public void SetValue(object destination,object value)
{
_lateBoundFieldSet(destination,value);
}
//如何给关注点赋值
public void Init(FieldInfo fieldInfo)
{
_fieldInfo = fieldInfo;
_name = fieldInfo.Name;
_memberType = fieldInfo.FieldType;
_lateBoundFieldGet = DelegateFactory.CreateGet(fieldInfo);// Emit or Expression 创建DynamicMethod
}
//关注Attributes
Type attributeType = typeof(xxxAttribute);
bool inherit = true;//继承
object[] attributes = _propertyInfo.GetCustomAttributes(attributeType,inherit);
object[] attributesNoInherit= _propertyInfo.GetCustomAttributes(attributeType);