C # Help me with some universal casting

I am trying to write a method to cover this object with an instance of a certain type. I started with this:

private static T TryCast<T>(object o)
{
    return (T) o;
}

As I enter, I know that this will not work, but it illustrates the concept. Now I will have problems when I have types that will not be automatically executed, for example string → DateTime. I tried to use the Convert Class to address these cases, but I just get a compile-time error instead of a runtime error. The following code gets a compilation error "Unable to express an expression of type" string "for input" T "

private static T TryCast<T>(object o)
{
    var typeName = typeof (T).FullName;

    switch (typeName)
    {
        case "System.String":
            return (T) Convert.ToString(o);
        default:
            return (T) o;
    }
}

Convert.ChangeType(), , , , , → DateTime, Convert.ToDateTime .

private static T TryCast<T>(object o)
{
    return (T)Convert.ChangeType(o, typeof(T));
}

, ? - , .

+5
1

Convert.ChangeType ; IConvertible.

, , T string.
, ( , Button TextBox).

, object:

return (T)(object)o.ToString();

( , ), , , T - string.

+6

All Articles