我在C#中搜索过静态变量,但我仍然没有得到它的用途.另外,如果我尝试在方法中声明变量,它将不会授予我执行此操作的权限.为什么?
我看过一些关于静态变量的例子.我已经看到我们不需要创建类的实例来访问变量,但这还不足以理解它的用途以及何时使用它.
第二件事
class Book
{
public static int myInt = 0;
}
public class Exercise
{
static void Main()
{
Book book = new Book();
Console.WriteLine(book.myInt); // Shows error. Why does it show me error?
// Can't I access the static variable
// by making the instance of a class?
Console.ReadKey();
}
}
Run Code Online (Sandbox Code Playgroud) 我知道,我知道...... Eric Lippert对这类问题的回答通常是" 因为它不值得设计,实施,测试和记录它的成本 ".
但是,我还是想要一个更好的解释......我正在阅读关于新C#4功能的博客文章,在关于COM Interop的部分中,以下部分引起了我的注意:
顺便说一句,这段代码使用了另外一个新功能:索引属性(仔细查看Range之后的那些方括号.)但是此功能仅适用于COM互操作; 您无法在C#4.0中创建自己的索引属性.
好的,但为什么呢?我已经知道并且后悔在C#中创建索引属性是不可能的,但这句话让我再次思考它.我可以看到几个很好的理由来实现它:
PropertyInfo.GetValue有一个index参数),所以遗憾的是我们无法在C#中利用它this属性名称可能没什么大不了的.它可以写出那种东西:
public class Foo
{
private string[] _values = new string[3];
public string Values[int index]
{
get { return _values[index]; }
set { _values[index] = value; }
}
}
Run Code Online (Sandbox Code Playgroud)
目前我知道的唯一解决方法是创建一个ValuesCollection实现索引器的内部类(例如),并更改Values属性以便它返回该内部类的实例.
这很容易做到,但很烦人......所以也许编译器可以为我们做!一个选项是生成一个实现索引器的内部类,并通过公共通用接口公开它:
// interface defined in the namespace System
public interface IIndexer<TIndex, TValue>
{
TValue this[TIndex index] { get; set; }
}
public …Run Code Online (Sandbox Code Playgroud) 有可能这样吗?我假设没有,但它对我来说很好看:
class MyClass {
public int Foo {
get { return m_foo; }
set {
// Bounds checking, or other things that prevent the use
// of an auto-implemented property
m_foo = value;
}
// Put the backing field actually *in* the scope of the property
// so that the rest of the class cannot access it.
private int m_foo;
}
void Method() {
m_foo = 42; // Can't touch this!
}
}
Run Code Online (Sandbox Code Playgroud)
当然我知道这个语法不正确,这不会编译.为了清楚地描绘我的想法,这是假设的未来C#.我为这个有点假设的问题道歉,但它对于Programmers.SE来说太具体了.
这样的东西可以在编译器中实现,它可以用于一个目的:只允许属性get和set …