Domanda

I'm trying to create a generic parsing method but I am stuck.
I want to be able to take in two types, an object of type1, and a default value of type2.
Then I want to try and parse the type1 object to the type2 object, if that doesn't work then return the default value.

Obviously the code below is invalid and doesn't work. But this is what I am going for. Does anyone know how to accomplish this in C#?

public static K TryGenericParse<T, K>(T objectToParse, K defaultValue)
{
    K returnValue;

    if (!K.TryParse(objectToParse, out returnValue))
        returnValue = defaultValue;

    return returnValue;
}
È stato utile?

Soluzione

You can use TypeConverter for this purpose. You can retrieve type convert using static method of TypeDescriptor, GetConverter.

public static TOuput TryGenericParse<TInput, TOuput>(TInput input)
{
    var converter = TypeDescriptor.GetConverter(typeof(TOuput));
    if (!converter.CanConvertFrom(typeof (TInput)))
        return default(TOuput);
    return (TOuput)converter.ConvertFrom(input);
}

bool bl = TryGenericParse<string, bool>("True");
double dbl = TryGenericParse<string, double>("3.222");
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top