Using a class's static member on a derived type?

后端 未结 4 1091
天涯浪人
天涯浪人 2020-12-29 02:11

Using Resharper 4.1, I have come across this interesting warning: \"Access to a static member of a type via a derived type\". Here is a code sample of where this occurs:

4条回答
  •  有刺的猬
    2020-12-29 02:37

    One place where it might be misleading is when the static is a factory method, e.g. the WebRequest class has a factory method Create which would allow this type of code to be written if accessed via a derived class.

    var request = (FtpWebRequest)HttpWebRequest.Create("ftp://ftp.example.com");
    

    Here request is of type FtpWebRequest but it's confusing because it looks like it was created from an HttpWebRequest (a sibling class) even though the Create method is actually defined on WebRequest (the base class). The following code is identical in meaning, but is clearer:

    var request = (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com");
    

    Ultimately there's no major problem accessing a static via a derived type, but code is often clearer by not doing so.

提交回复
热议问题