通用的TryParse [英] Generic TryParse

查看:77
本文介绍了通用的TryParse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个使用的TryParse检查一个字符串是一个给定类型的通用扩展名:

 公共静态布尔为< T>(这串输入)
{
    ŤNOTUSED;
    返回T.TryParse(输入,出NOTUSED);
}

这将无法编译,因为它不能解析符号的TryParse

据我了解,'的TryParse不是任何接口的一部分。

这是可能做到呢?

更新:

使用下面的答案,我想出了:

 公共静态布尔为< T>(这串输入)
{
    尝试
    {
        。TypeDescriptor.GetConverter(typeof运算(T))ConvertFromString(输入);
    }
    抓住
    {
        返回false;
    }    返回true;
}

它工作得很好,但我认为以这种方式使用异常感觉不对我。

UPDATE2:

修改传递类型而不是使用泛型:

 公共静态布尔是(这个字符串输入型TARGETTYPE)
{
    尝试
    {
        TypeDescriptor.GetConverter(TARGETTYPE).ConvertFromString(输入);
        返回true;
    }
    抓住
    {
        返回false;
    }
}


解决方案

您应该使用TypeDescriptor类:

 公共静态牛逼转换< T>(这串输入)
{
    VAR器= TypeDescriptor.GetConverter(typeof运算(T));
    如果(变频器!= NULL)
    {
        //演员ConvertFromString(字符串文本):对象(T)
        回报(T)converter.ConvertFromString(输入);
    }
    返回默认(T);
}

当然,如果转换失败,所以你会想尝试/捕获它,这将引发异常。

I am trying to create a generic extension that uses 'TryParse' to check if a string is a given type:

public static bool Is<T>(this string input)
{
    T notUsed;
    return T.TryParse(input, out notUsed);
}

this won't compile as it cannot resolve symbol 'TryParse'

As I understand, 'TryParse' is not part of any interface.

Is this possible to do at all?

Update:

Using the answers below I have come up with:

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

    return true;
}

It works quite well but I think using exceptions in that way doesn't feel right to me.

Update2:

Modified to pass type rather than use generics:

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

解决方案

You should use the TypeDescriptor class:

public static T Convert<T>(this string input)
{
    var converter = TypeDescriptor.GetConverter(typeof(T));
    if(converter != null)
    {
        //Cast ConvertFromString(string text) : object to (T)
        return (T)converter.ConvertFromString(input);
    }
    return default(T);
}

of course this will throw an exception if the conversion fails so you will want to try/catch it.

这篇关于通用的TryParse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆