在派生类中使用类的静态成员? [英] Using a class's static member on a derived type?

查看:94
本文介绍了在派生类中使用类的静态成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ReSharper的4.1,我也碰到过这个有趣的警告。这里是发生这种情况的一个代码示例:

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:

class A {
    public static void SomethingStatic() {
       //[do that thing you do...]
    }
}

class B : A {
}

class SampleUsage {
    public static void Usage() {
        B.SomethingStatic(); // <-- Resharper warning occurs here
    }
}



请问有人知道问题有(如果有的话),使利用B使用A的静态成员的时候?

Does anybody know what issues there are (if any) when making use of A's static members via B?

推荐答案

一个地方,它可能会被误导是当静是一个工厂的方法,例如在的WebRequest 类有一个工厂方法创建这将允许写入这种类型的代码,如果通过一个派生类访问

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");

下面要求的类型为的FtpWebRequest ,而是因为它看起来就像是从的HttpWebRequest (兄弟姐妹类)创建它的混乱,即使创建方法实际上是定义在的WebRequest (基类)。下面的代码是意义相同,但更清楚:

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.

这篇关于在派生类中使用类的静态成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆