什么是C#相当于PHP的“self ::”?

在C#中,当我想从该类的另一个静态方法调用类的静态方法时,是否有一个我可以使用的generics前缀 ,例如PHP的self::而不是类名?

所以在下面的例子中,我不是说Customer.DatabaseConnectionExists() ,而是如何说出类似Self.DatabaseConnectionExists()东西,所以后来如果我更改类的名称我不必更改所有的前缀?

 class Customer { public string FirstName { get; set; } public string LastName { get; set; } public static Customer GetCurrentCustomer() { if (Customer.DatabaseConnectionExists()) { return new Customer { FirstName = "Jim", LastName = "Smith" }; } else { throw new Exception("Database connection does not exist."); } } public static bool DatabaseConnectionExists() { return true; } } 

没有真正的等价物 – 你必须指定类名,即

 Customer.DatabaseConnectionExists() 

或者完全错过预选赛,即

 DatabaseConnectionExists() 

后一种调用方式是可取的,因为它更简单并且不会失去任何意义。 此外,它更多内联方法调用实例(即通过InstanceMethod()调用而不是 this.InstanceMethod() ,这是过于冗长的)。

如果你从类中调用方法,你不需要像:: Self那样指定任何东西,只需要方法名称即可。

 class Customer { public string FirstName { get; set; } public string LastName { get; set; } public static Customer GetCurrentCustomer() { if (DatabaseConnectionExists()) { return new Customer { FirstName = "Jim", LastName = "Smith" }; } else { throw new Exception("Database connection does not exist."); } } public static bool DatabaseConnectionExists() { return true; } } 

把它留下来吧。 DatabaseConnectionExists在类中定义。

只需调用它,不带任何前缀。

不,没有。 但是使用重构工具,更改类的名称不应该太担心你。