dan*_*die 6 .net static language-design const
我一直在编写代码而没有意识到为什么我可以在静态方法中访问常量值.
为什么可以在const不声明值的情况下访问值static?
例如,IMAGE_FILE_EXTENSION在内部打电话是合法的AddImageToDocument(...)
public abstract class ImageDocumentReplacer : DocumentReplacer
{
private const string IMAGE_FILE_EXTENSION = ".tif";
private static void AddImageToDocument(int documentId, string separatedPath)
{
Console.WriteLine(IMAGE_FILE_EXTENSION);
}
}
Run Code Online (Sandbox Code Playgroud)
Meh*_*ari 18
const成员是含蓄的static.它们属于类而不是特定的实例.因此,你不能使用this.myConstant但是MyClass.myConstant.
引用C#3.0规范(第10.4节常量):
尽管常量被视为
static成员,一个常数声明 既不要求也允许一个static修正.同一修饰符在常量声明中多次出现是错误的.