Cannot implicitly convert type 'System.Version' to 'System.Net.HttpVersion'

StackOverflow https://stackoverflow.com/questions/21388058

  •  03-10-2022
  •  | 
  •  

سؤال

Consider the following code:

void Main()
{
    HttpVersion version;
    string s = "HTTP/1.1";
    version = s == "HTTP/1.1" ? HttpVersion.Version11 : HttpVersion.Version10;
}

This throws the error

Cannot implicitly convert type 'System.Version' to 'System.Net.HttpVersion'

even though System.Version is nowhere inferred and isn't even part of HttpVersion's inheritance.

Explicit casts

void Main()
{
    HttpVersion version;
    string s = "HTTP/1.1";
    version = s == "HTTP/1.1" ? (HttpVersion) HttpVersion.Version11 : (HttpVersion) HttpVersion.Version10;
}

or explicit namespace naming

void Main()
{
    System.Net.HttpVersion version;
    string s = "HTTP/1.1";
    version = s == "HTTP/1.1" ? System.Net.HttpVersion.Version11 : System.Net.HttpVersion.Version10;
}

don't make a difference.

The question is simple: why is System.Version interfering with what should be an unrelated class?

هل كانت مفيدة؟

المحلول

The Version10 and Version11 static fields of HttpVersion return System.Version objects, not HttpVersion objects. So it's not technically unrelated.

Now as for WHY it does that, I have absolutely no idea. But you'll note that the places where it is used (such as HttpWebRequest.ProtocolVersion) use System.Version as well. So that's what you want to be using.

To me, it kind of looks kind of like HttpVersion should have been a static class as it has no instance members that are not inherited from Object...

نصائح أخرى

HttpVersion.Version11 and HttpVersion.Version10 both return a Version object, which you're trying to store in an HttpVersion variable.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top