c# - Generics explicit conversion -
i implemented explicit conversion string object called foo.
so => foo f = (foo)"foo data"; works
i need implement function cast string generic t, t in case foo datatype.
public t get<t>(object o){ // return false if (typeof(t).isassignablefrom(typeof(string))) { // when pass if above throws invalid cast exception return (t)(object)str; } return null; } // when call this, generated error // invalid cast 'system.string' foo foo myobj = get<foo>("another foo object"); // when use dynamic keyword works c# 4.0+ feature, function in older framework return (t)(dynamic)str;
an example uses reflection:
class program { static void main(string[] args) { foo myobj = typeresolver.get<foo>("foo data"); } } class typeresolver { public static t get<t>(object obj) { if (typeof(t).canexplicitlycastfrom<string>()) { return obj.castto<t>(); } return default(t); } } public static class extensions { public static bool canexplicitlycastfrom<t>(this type type) { if (type == null) throw new argumentnullexception("type"); var paramtype = typeof(t); var castoperator = type.getmethod("op_explicit", new[] { paramtype }); if (castoperator == null) return false; var parametres = castoperator.getparameters(); var paramtype = parametres[0]; if (paramtype.parametertype == typeof(t)) return true; else return false; } public static t castto<t>(this object obj) { var castoperator = typeof(t).getmethod("op_explicit", new[] { typeof(string) }); if (castoperator == null) throw new invalidcastexception("can't cast " + typeof(t).name); return (t)castoperator.invoke(null, new[] { obj }); } }
Comments
Post a Comment