.Net 小技巧(一)

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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值