mardi 4 décembre 2018

"where this : class" wrong syntax [on hold]

public static class Extensions
{
    public static T2 TryCast<T, T2>(this T parent)
        where T : class
        where T2 : class
    {
        T2 child = (T2)Activator.CreateInstance(typeof(T2));
        // Code
        return child;
    }

    public static T TryCast<T>(this object parent)
    {
        T child = (T)Activator.CreateInstance(typeof(T));
        // Code
        return child;
    }
}

The first TryCast can be used like someString.TryCast<string, someClassToCastTo>(). This is not optimal, as one has to specify the class of the calling variable.

I like the fact that the second TryCast can be used as someString.TryCast<someClassToCastTo>(), but it is not constrained to only classes, as "where this : class" returns syntax error", which means that it will appear on variables like int, char, etc.

How can I restrict the second method to be used only by classes, similar to the first method?





Aucun commentaire:

Enregistrer un commentaire