Generic type conversion FROM string

前端 未结 11 681
终归单人心
终归单人心 2020-11-27 09:47

I have a class that I want to use to store \"properties\" for another class. These properties simply have a name and a value. Ideally, what I would like is to be able to add

11条回答
  •  广开言路
    2020-11-27 09:47

    With inspiration from the Bob's answer, these extensions also support null value conversion and all primitive conversion back and fourth.

    public static class ConversionExtensions
    {
            public static object Convert(this object value, Type t)
            {
                Type underlyingType = Nullable.GetUnderlyingType(t);
    
                if (underlyingType != null && value == null)
                {
                    return null;
                }
                Type basetype = underlyingType == null ? t : underlyingType;
                return System.Convert.ChangeType(value, basetype);
            }
    
            public static T Convert(this object value)
            {
                return (T)value.Convert(typeof(T));
            }
    }
    

    Examples

                string stringValue = null;
                int? intResult = stringValue.Convert();
    
                int? intValue = null;
                var strResult = intValue.Convert();
    

提交回复
热议问题