Type Assignment at Run Time

I have a variable x of type T and a value that is in a string. For example, I have:

bool x, value = "True" int x, value = "1" 
  • Is there a general way to assign / parse / deserialize an x โ€‹โ€‹value?

Note that T can be a reference or a primitive type!

+4
source share
3 answers

You can use the Convert.ChangeType method .

This will cover all base type conversions.

Example: var i = Convert.ChangeType("1", typeof(int));

You can also see the IConvertible interface , which you can use to convert your own objects from or to another type.

Finally, as codymanix said, you can rely on OOB XmlSerialization or Binary Serialization to serialize your objects.

[edit] you can check at compile time if the target type is converted by transferring the convert.ChangeType method to the utility class as follows:

 public static class ConvertUtility { public static T Convert<T>(object source) where T : IConvertible { return (T)System.Convert.ChangeType(source, typeof(T)); } } 
+5
source

I wrote this thought-based approach some time ago. This is relatively unverified. He is looking for methods called Parse and TryParse . And I did not care about the language dependent (in) dependent parsing.

  private static class ParseDelegateStore<T> { public static ParseDelegate<T> Parse; public static TryParseDelegate<T> TryParse; } private delegate T ParseDelegate<T>(string s); private delegate bool TryParseDelegate<T>(string s, out T result); public static T Parse<T>(string s) { ParseDelegate<T> parse = ParseDelegateStore<T>.Parse; if (parse == null) { parse = (ParseDelegate<T>)Delegate.CreateDelegate(typeof(ParseDelegate<T>), typeof(T), "Parse", true); ParseDelegateStore<T>.Parse = parse; } return parse(s); } public static bool TryParse<T>(string s, out T result) { TryParseDelegate<T> tryParse = ParseDelegateStore<T>.TryParse; if (tryParse == null) { tryParse = (TryParseDelegate<T>)Delegate.CreateDelegate(typeof(TryParseDelegate<T>), typeof(T), "TryParse", true); ParseDelegateStore<T>.TryParse = tryParse; } return tryParse(s, out result); } 
+1
source

I know differently than doing:

 object x; if (theType==typeof(int)) x = int.parse(myString); else if (theType==typeof(bool)) x = bool.Parse(myString); // and so on for other types.. 

Also note that serialized data must contain type names, since otherwise you have no way to find out if the type is "123", the type is int or unsigned short, or something else, or, for example, "Red" is an enumeration value, Color object or string.

You can use XmlSerializer or BinaryFormatter to serialize / deserialize your objects, which makes all of this logic right for you.

0
source

Source: https://habr.com/ru/post/1339180/


All Articles