zoukankan      html  css  js  c++  java
  • 静态类、静态方法的使用

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace _Test
    {
    
        class Program
        {
            static void Main(string[] args)
            {
                //调用实例成员
                Person p = new Person();
                p.M1();//实例方法,调用的时候必须创建实例对象。
                Person.M2();//静态方法,只能通过类名直接调用。
    
                Student.M3();//静态类中的静态方法只能通过类名调用。
                
    
                Console.WriteLine();
                Console.ReadKey();
            }
        }
    
    
        public static class Student  //静态类
        {
            private static string _name;
    
            public static string Name
            {
                get { return Student._name; }
                set { Student._name = value; }
            }
    
            public static void M3()
            {
                Console.WriteLine("Hello World");
            }
    
        }
    
    
        public class Person //非静态类
        {
            private static string _name;
    
            public static string Name
            {
                get { return Person._name; }
                set { Person._name = value; }
            }
            private char _gender;
    
            public char Gender
            {
                get { return _gender; }
                set { _gender = value; }
            }
            public void M1() //非静态方法
            {
    
                Console.WriteLine("我是非静态的方法");
            }
            public static void M2() //静态方法
            {
    
                Console.WriteLine("我是一个静态方法");
            }
        }
    
    }
    

     语法规则:

    1静态类与非静态类基本相同,但存在一个区别:静态类不能实例化。也就是说,不能使用 new 关键字创建静态类类型的变量。因为没有实例变量,所以要使用类名本身访问静态类的成员。

    2静态类的特性:

    • 仅包含静态成员。

    • 无法实例化。

    • 是密封的。

    • 不能包含实例构造函数。

  • 相关阅读:
    分析函数
    Orcal函数
    归档日志
    JSP数据交互
    JSP
    接口
    JAVA修饰符
    QuicKHit
    Java 三章错题
    Java 多态
  • 原文地址:https://www.cnblogs.com/hao-1234-1234/p/6107909.html
Copyright © 2011-2022 走看看