c# - 为什么 "this"可以,但 "this"(在另一种方法中)不行?

标签 c# asp.net

<分区>

这来自与 aspx 文件关联的 c# .net (.aspx.cs) 文件。
为什么“this”可以,但“this”(以另一种方法)不行? 我在第二种方法中包含了一个快照图像以显示红线,以表明编译器不喜欢第一种方法中未显示错误的内容。

enter image description here

最佳答案

this 用于引用类的当前实例。
在静态方法中,没有要引用的当前实例。

在第一个示例中,它引用了类 Resource_Windows_ContractEdit 的当前实例。
在第二个示例中,该方法是静态的,因此应该在没有类实例的情况下调用它。因此在该静态方法中你不能使用 this

C# Reference 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/

相关文章:

c# - 代码覆盖率工具和 Visual Studio 2008 Pro

c# - 具有多个 float 的固定位置

c# - 要打印的小数位数的站点全局规则

c# - ASP.NET C# GridView 选项卡索引问题

javascript - 关于从 ASP .NET 用户控件迁移到 .NET 3.5 母版页技术的问题

c# - 使用 XmlSerializer 时自动缩小属性/元素名称

c# - Convert.FromBase64String c# 上的 FormatException

c# - Entity Framework 6 Guid 生成空?

c# - 如何在 c#.net 中将结构转换为字节数组,但结构大小仅在运行时定义

递归内部函数的 C# 命名约定?