Generic type conversion FROM string

前端 未结 11 646
终归单人心
终归单人心 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:59

    Yet another variation. Handles Nullables, as well as situations where the string is null and T is not nullable.

    public class TypedProperty : Property where T : IConvertible
    {
        public T TypedValue
        {
            get
            {
                if (base.Value == null) return default(T);
                var type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
                return (T)Convert.ChangeType(base.Value, type);
            }
            set { base.Value = value.ToString(); }
        }
    }
    

提交回复
热议问题