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

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

I have this XML document


False



        
相关标签:
3条回答
  • 2021-02-15 12:24

    You can use Convert.ChangeType :

    object value = Convert.ChangeType(stringValue, destinationType);
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2021-02-15 12:25

    You can't do exactly what you're trying to do. First, the typeof keyword does not allow for dynamic evaluation at runtime. There are means by which to do this using reflection, with methods like Type.GetType(string), but the Type objects returned from these reflective functions can't be used for operations like casting.

    What you need to do is provide a means of converting your type to and from a string representation. There is no automatic conversion from any arbitrary type. For your example, you can use bool.Parse or bool.TryParse, but those are specific to the bool type. There are similar methods on most primitive types.

    0 讨论(0)
提交回复
热议问题