Type contraint problem of C#

Posted by user351565 on Stack Overflow See other posts from Stack Overflow or by user351565
Published on 2010-05-27T04:05:39Z Indexed on 2010/05/27 4:11 UTC
Read the original article Hit count: 127

Filed under:
|
|
|

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.InSubclassOf(typeof(CodeObject))) return ((CodeObject)val).Code;
}

static T ConvertToObject<T>(string str) {
 Type type = typeof(T);
 if (type == typeof(string)) return (T)(object)val;
 if (type == typeof(int)) return (T)(object)int.Parse(val);
 if (type.InSubclassOf(typeof(CodeObject))) return Codes.Get<T>(val);
}

where CodeObject is a base class of Employees, Offices ..., which can fetch by static method Godes.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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about reflection