简体   繁体   中英

How to write a generic function in c#?

I am trying to write a generic function in c# which tries to parse a string based on the type.

Here is what I tried

    public static T convertString<T>(string raw)
    {
        if( typeof(T) == DateTime ){
            DateTime final;
            DateTime.TryParseExact(raw, "yyyy-mm-dd hh:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out final);
            return final;
         }

        if( typeof(T) == int ){
            int final;
            Int32.TryParse(raw, out final);
            return final;
        }

    }

How can I correct this function to work?

you can try something like that :

public static T ConvertFromString<T>(string raw)
{
    return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(raw);
}

// Usage
var date = ConvertFromString<DateTime>("2015/01/01");
var number = ConvertFromString<int>("2015");

Edit: Support for TryConvert

Otherwise you can create a function that will try to convert the input string:

public static bool TryConvertFromString<T>(string raw, out T result)
{
    result = default(T);
    var converter = TypeDescriptor.GetConverter(typeof (T));
    if (!converter.IsValid(raw)) return false;

    result = (T)converter.ConvertFromString(raw);
    return true;
}

// Usage
DateTime result;
if (!TryConvertFromString<DateTime>("this is not a date", out result))
{

}

You can even do this more generic and not rely on a string parameter provided the type U implements IConvertible - this means you have to specify two type parameters though:

 public static T ConvertValue<T,U>(U value) where U : IConvertible
    {
        return (T)Convert.ChangeType(value, typeof(T));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM