<分区>
这来自与 aspx 文件关联的 c# .net (.aspx.cs) 文件。
为什么“this”可以,但“this”(以另一种方法)不行?
我在第二种方法中包含了一个快照图像以显示红线,以表明编译器不喜欢第一种方法中未显示错误的内容。
<分区>
这来自与 aspx 文件关联的 c# .net (.aspx.cs) 文件。
为什么“this”可以,但“this”(以另一种方法)不行?
我在第二种方法中包含了一个快照图像以显示红线,以表明编译器不喜欢第一种方法中未显示错误的内容。
最佳答案
this
用于引用类的当前实例。
在静态方法中,没有要引用的当前实例。
在第一个示例中,它引用了类 Resource_Windows_ContractEdit 的当前实例。
在第二个示例中,该方法是静态的,因此应该在没有类实例的情况下调用它。因此在该静态方法中你不能使用 this
一个人为的例子
class Example1
{
// static. could be used by static methods and it is shared between all instances
private static int counter = 0;
// instance variable, exists with different indipendent storage for every instance
private int v;
public Example1()
{
// We can use the static variable because it is shared between all instances..
counter = counter + 1;
}
public int SumValue(int x)
{
// Sum only for the first 10 instances of this class..
// Yes weird, but it is just a contrived example
if(Example1.counter < 10)
this.v = this.v + x:
return this.v;
}
// Cannot use the this keyword neither the instance internal variables
// Could use the static variables
public static int GetCurrentInstanceCounter()
{
return counter;
}
}
void Main()
{
Example1 a = new Example1();
// a is an instance of class Example1 and could use the this keyword
int result = a.sumValue(10);
Console.WriteLine(result.ToString());
// GetCurrentInstanceCounter is static, no instance required to call it, just the class name
int c = Example1.GetCurrentInstanceCounter();
Console.WriteLine("Created " + c.ToString() + " instances of Example1");
}
关于c# - 为什么 "this"可以,但 "this"(在另一种方法中)不行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22106082/