开发者

Generic structure for performing string conversion when data binding

a little while ago i was reading an article about a series of class that were created that handled the conversion of strings into a generic type. Below is a mock class structure. Basically if you set the StringValue it will perform some conversion into type T

public class MyClass<T>
{
    public string StringValue {get;set;}
    public T Value {get开发者_运维技巧;set;}
}

I cannot remember the article that i was reading, or the name of the class i was reading about. Is this already implemented in the framework? Or shall i create my own?


Here is a little trick to convert strings into simple types (struct 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));
    }
}


This does not exist in the .NET framework. You'd have to create your own.


I don't remember anything like that, but if it did exist it would almost certainly be an abstract class or interface, still requiring you to implement the conversion logic yourself. There's really no possible way for Microsoft to write code that can accept a string representation of classes that haven't even been written yet and just know how to properly construct that class.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜