General structure for converting strings in data binding

some time ago I read an article about a series of classes that were created that handled converting strings to a generic type. The following is the structure of the class. Basically, if you set StringValue, it will do some conversion to type T

public class MyClass<T> { public string StringValue {get;set;} public T Value {get;set;} } 

I can’t remember the article I read, or the name of the class I read about. Is it already implemented in the framework? Or should I create my own?

+4
source share
3 answers

Here's a little trick for converting strings to simple types (structure types):

 public T GetValueAs<T>(string sValue) where T : struct { if (string.IsNullOrEmpty(sValue)) { return default(T); } else { return (T)Convert.ChangeType(sValue, typeof(T)); } } 
0
source

It does not exist in the .NET Framework. You will need to create your own.

+1
source

I don't remember anything like that, but if it really existed, it would almost certainly be an abstract class or interface, still requiring you to implement the conversion logic yourself. In fact, Microsoft cannot write code that can take a string representation of classes that have not yet been written, and just know how to properly build this class.

When you think about it, abstract functionality is already available in Func<string, T> or in one of many serialization formats (xml, json, protobuf, etc.).

-1
source

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


All Articles