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

后端 未结 5 1274
情深已故
情深已故 2021-01-04 12:46

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

相关标签:
5条回答
  • 2021-01-04 13:27

    Just leave it out. DatabaseConnectionExists is defined inside the class.

    0 讨论(0)
  • 2021-01-04 13:33

    Just call it without any prefix.

    0 讨论(0)
  • 2021-01-04 13:35

    There's no real equivalent - you have to either specify the class name, i.e.

    Customer.DatabaseConnectionExists()
    

    or miss out the qualifier altogether, i.e.

    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 (i.e. calling by InstanceMethod() and not this.InstanceMethod(), which is overly verbose).

    0 讨论(0)
  • 2021-01-04 13:46

    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.

    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;
        }
    }
    
    0 讨论(0)
  • 2021-01-04 13:48

    No, there isn´t. But with the refactor tools, changing a name of a class should not worry you too much.

    0 讨论(0)
提交回复
热议问题