Generic type conversion FROM string

前端 未结 11 667
终归单人心
终归单人心 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 10:06

    Check the static Nullable.GetUnderlyingType. - If the underlying type is null, then the template parameter is not Nullable, and we can use that type directly - If the underlying type is not null, then use the underlying type in the conversion.

    Seems to work for me:

    public object Get( string _toparse, Type _t )
    {
        // Test for Nullable and return the base type instead:
        Type undertype = Nullable.GetUnderlyingType(_t);
        Type basetype = undertype == null ? _t : undertype;
        return Convert.ChangeType(_toparse, basetype);
    }
    
    public T Get(string _key)
    {
        return (T)Get(_key, typeof(T));
    }
    
    public void test()
    {
        int x = Get("14");
        int? nx = Get>("14");
    }
    

提交回复
热议问题