How to dynamically cast an object of type string to an object of type T

前端 未结 3 1850
北海茫月
北海茫月 2021-02-15 12:17

I have this XML document


False

         


        
3条回答
  •  伪装坚强ぢ
    2021-02-15 12:24

    The simple solution, assuming there is a limited number of possible types;

    object GetValueObject(string type, string value)
    {
      switch (type)
      {
        case "System.Boolean":
          return Boolean.Parse(value);
        case "System.Int32":
          return Int32.Parse(value);
        ...
        default:
          return value;
      }
    }  
    
    var type = publishNode.Attributes["Type"].value;
    var value = publishNode.InnerText;
    var valueObject = GetValueObject(type, value);
    

提交回复
热议问题