上周末我遇到了一个开源项目,当时我碰到了一些代码,让我很困惑地查看了C#规范中的用法.
问题中的代码如下:
internal static class SomeStaticClass
{
private const int CommonlyUsedValue = 42;
internal static string UseCommonlyUsedValue(...)
{
// some code
value = CommonlyUsedValue + ...;
return value.ToString();
}
}
Run Code Online (Sandbox Code Playgroud)
我被猝不及防,因为这似乎是静态函数使用的非静态字段,有些如何在静态类中编译得很好!
规范声明(§10.4):
常量声明可以包括一组属性(§17),一个新修饰符(§10.3.4),以及四个访问修饰符的有效组合(§10.3.5).属性和修饰符适用于constant-declaration声明的所有成员.尽管常量被认为是静态成员,但常量声明既不需要也不允许使用静态修饰符.同一修饰符在常量声明中多次出现是错误的.
所以现在它更有意义,因为常量被认为是静态成员,但句子的其余部分对我来说有点令人惊讶.为什么常量声明既不需要也不允许使用静态修饰符?不可否认,我不知道这个规范是否足以让它立即变得有意义,但为什么决定不强制常量使用静态修饰符如果它们被认为是静态的?
查看该段落中的最后一句,我无法弄清楚它是否直接与前一个语句有关,并且在常量上有一些隐式静态修饰符,或者它是否作为常量的另一个规则.任何人都可以帮我解决这个问题吗?
Possible Duplicate:
C#.NET - Why do members of a static class need to be declared as static? Why isn't it just implicit?
I am getting an interesting error, in that when I call a method (which I don't explicitly declare as static) from within a statically declared class, I get a message saying
An object reference is required for the non-static field, method, or property 'MangoTree.Twitter.OAuthClient.PerformRequest(System.Collections.Generic.Dictionary, string, string, string, MangoTree.Twitter.OAuthClient.RequestType)'
当我将该方法显式声明为静态时,错误就会消失,并且我可以从类声明中删除 static 修饰符,错误就会消失。让我感到困惑的是,我的印象是,当我将类声明为静态时,类中的所有内容都应该自动是静态的,而无需我显式声明它。