简体   繁体   English

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

[英]What is the C# equivalent to PHP's “self::”?

In C# when I want to call a static method of a class from another static method of that class, is there a generic prefix that I can use such as PHP's self:: instead of the class name? 在C#中,当我想从该类的另一个静态方法调用类的静态方法时,是否有一个我可以使用的泛型前缀 ,例如PHP的self::而不是类名?

So in the below example, instead of saying Customer.DatabaseConnectionExists() , how can I say something like Self.DatabaseConnectionExists() so eg later if I change the name of the class I don't have to go change all the prefixes? 所以在下面的例子中,我不是说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;
    }
}

There's no real equivalent - you have to either specify the class name, ie 没有真正的等价物 - 你必须指定类名,即

Customer.DatabaseConnectionExists()

or miss out the qualifier altogether, ie 或完全错过预选赛,即

DatabaseConnectionExists()

The latter style of calling is advisable since it's simpler and doesn't lose any meaning. 后一种调用方式是可取的,因为它更简单并且不会失去任何意义。 Also, it's more inline with method calling in instances (ie calling by InstanceMethod() and not this.InstanceMethod() , which is overly verbose). 此外,它更多内联方法调用实例(即由InstanceMethod()调用,而不是 this.InstanceMethod() ,这是过于冗长)。

If you're calling the method from inside the class, you don't need to specify anything like ::Self, just the method name will do. 如果你从类中调用方法,你不需要像:: 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;
    }
}

Just leave it out. 把它留下来吧。 DatabaseConnectionExists is defined inside the class. DatabaseConnectionExists在类中定义。

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

No, there isn´t. 不,没有。 But with the refactor tools, changing a name of a class should not worry you too much. 但是使用重构工具,更改类的名称不应该太担心你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM