Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

c# - 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 (T)v.ToString(); // Cannot convert type 'string' to 'T'  
    } else try {
      return (T)v;
    } catch (InvalidCastException) {
    return null;
    }
}

Also let me know if this is some sort of unforgivable sin. I'm using it to deal with some data structures that could have mixed types.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You basically need to go via object when casting to a generic type:

return (T)(object) v.ToString()

and

return (T)(object) v;

I would use is rather than catching an InvalidCastException though.

See Eric Lippert's recent blog post for more details of why this is necessary.

In particular:

Because the compiler knows that the only way this conversion could possibly succeed is if U is bool, but U can be anything! The compiler assumes that most of the time U is not going to be constructed with bool, and therefore this code is almost certainly an error, and the compiler is bringing that fact to your attention.

(Substitute T for U and string for bool...)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...