22
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ジェネリック使ったTryParse

Posted at

TypeDescriptor クラスを使用

第2引数resultに初期値を設定したくなかったので、outからrefに変更。

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;
        }
    }
}

サンプル

int i=0, j=0;
float f = 0.0f;
double d = 0.0d;
decimal m = 0.0m;
bool a = false;

// int変換
a = MyTryParse.TryParse<int>("a", ref i);
Console.WriteLine(a + ":" + i); // False:0
a = MyTryParse.TryParse<int>("1", ref i);
Console.WriteLine(a + ":" + i); // True:1
a = MyTryParse.TryParse<int>("0.1", ref j);
Console.WriteLine(a + ":" + j); // False:0
// float変換
a = MyTryParse.TryParse<float>("0.1", ref f);
Console.WriteLine(a + ":" + f); // True:0.1
// double変換
a = MyTryParse.TryParse<double>("0.1", ref d);
Console.WriteLine(a + ":" + d); // True:0.1
// decimal変換
a = MyTryParse.TryParse<decimal>("79228162514264337593543950335", ref m);
Console.WriteLine(a + ":" + m); // True:79228162514264337593543950335

型変換できるかどうかだけ確認する

Generic TryParse

public static bool Is<T>(this string input)
{
    try
    {
        TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(input);
    }
    catch
    {
        return false;
    }

    return true;
}

ジェネリックを使わない

public static bool Is(this string input, Type targetType)
{
    try
    {
        TypeDescriptor.GetConverter(targetType).ConvertFromString(input);
        return true;
    }
    catch
    {
        return false;
    }
}
22
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?