.Net 小技巧(一)

来源:互联网 发布:福建 土豪 知乎 编辑:程序博客网 时间:2024/05/19 20:37

1.net类型与类型之间进行安全的转换

//获取类型的TypeConverterType 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<>类型的Typebool isNullableType=type.IsGenericType && (type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)));

3.PropertyInfo 一般那些对我们有意义

//关注PropertyInfoPropertyInfo _propertyInfo;//关注Namesring _name;//关注Property的TypeType _memberType;//关注Get取值方法LateBoundPropertyGet _lateBoundPropertyGet;//Emit or Expression 动态代码构造委托public object GetValue(object source){    return _lateBoundPropertyGet(source);}//关注Set赋值方法LateBoundPropertySet _lateBoundPropertySet;//Emit or Expression 创建DynamicMethodpublic 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);}//关注AttributesType attributeType = typeof(xxxAttribute);bool inherit = true;//继承object[] attributes = _propertyInfo.GetCustomAttributes(attributeType,inherit);object[] attributesNoInherit= _propertyInfo.GetCustomAttributes(attributeType);

4.FieldInfo 一般那些对我们有意义

//关注 FieldInfoFieldInfo _fieldInfo;//关注 Namestring _name;//关注 Field 的TypeType _memberType;//关注 Get LateBoundFieldGet _lateBoundFieldGet;public object GetValue(object source){    return _lateBoundFieldGet(source);}//关注 SetLateBoundFieldSet _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}//关注AttributesType attributeType = typeof(xxxAttribute);bool inherit = true;//继承object[] attributes = _propertyInfo.GetCustomAttributes(attributeType,inherit);object[] attributesNoInherit= _propertyInfo.GetCustomAttributes(attributeType);
0 0
原创粉丝点击