I meet a problem about type contraint of c# now.
I wrote a pair of methods that can convert object to string and convert string to object. ex.
static string ConvertToString(Type type, object val) {
if (type == typeof(string)) return (string)val;
if (type == typeof(int)) return val.ToString();
if (type.IsSubclassOf(typeof(CodeObject))) return ((CodeObject)val).Code;
}
static T ConvertToObject<T>(string val) {
Type type = typeof(T);
if (type == typeof(string)) return (T)(object)val;
if (type == typeof(int)) return (T)(object)int.Parse(val);
if (type.IsSubclassOf(typeof(CodeObject))) return Codes.Get<T>(val);
}
where CodeObject is a base class of Employees, Offices ..., which can fetch by static method Codes.Get where T: CodeObject
but the code above cannot be compiled because error #CS0314
the generic type T of method ConvertToObject have no any constraint but Codes.Get request T must be subclass of CodeObject
i tried use overloading to solve the problem but not ok.
is there any way to clear up the problem? like reflection?