mizuneko
3/11/2015 - 5:52 AM

TryParse.cs

using System.ComponentModel;

public static class MyTryParse
{
    public static bool TryParse<T>(string input, ref T result)
    {
        try
        {
            var converter = TypeDescriptor.GetConverter(typeof(T));
            if(converter != null)
            {
                //ConvertFromString(string text)の戻りは object なので T型でキャストする
                result = (T)converter.ConvertFromString(input);
                return true;
            }
            return false;
        }
        catch
        {
            return false;
        }
    }
}