Casting string to generic type that is a string
问题 I'm writing a method to do a intelligent type conversion - using ToString() if the type parameter happens to be a string, otherwise casting but returning null if the cast doesn't work. Basically gets as much information out of v it can without throwing an exception. I check that T is indeed a string before I attempt the cast, but the compiler is still not a fan: Cannot convert type 'string' to 'T' And here's my method: public T? Convert<T>(object v) { if (typeof(T) == typeof(string)) { return