search
HomeBackend DevelopmentC#.Net TutorialC# basic knowledge compilation: basic knowledge (10) static

If you want to access the methods or properties of a certain class, you must first instantiate the class, and then use the object of the class plus the . sign to access it. For example:
There is a user class and a class that handles passwords (encryption and decryption). After a user instance is not generated, the password class needs to encrypt and decrypt the password.

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace YYS.CSharpStudy.MainConsole.Static
{
    /// <summary>
    /// 用户类
    /// </summary>
    public class User
    {
        //加密解密用到的Key
        private string key = "20120719";
        //加密解密用到的向量
        private string ivalue = "12345678";

        private string userName;

        private string userEncryptPassword;

        private string userDecryptPassword;

        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName
        {
            get
            {
                return userName;
            }
        }
        /// <summary>
        /// 用户密码,加密后的密码
        /// </summary>
        public string UserEncryptPassword
        {
            get
            {
                return userEncryptPassword;
            }
        }
        /// <summary>
        /// 用户密码,解密后的密码
        /// </summary>
        public string UserDecryptPassword
        {
            get
            {
                DES des = new DES();

                this.userDecryptPassword = des.Decrypt(userEncryptPassword, key, ivalue);

                return userDecryptPassword;
            }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="userPassword"></param>
        public User(string userName, string userPassword)
        {
            this.userName = userName;

            DES des = new DES();

            this.userEncryptPassword = des.Encrypt(userPassword, key, ivalue);
        }
    }

    /// <summary>
    /// 处理密码的类
    /// </summary>
    public class DES
    {
        /// <summary>
        /// 加密字符串
        /// </summary>
        public string Encrypt(string sourceString, string key, string iv)
        {
            try
            {
                byte[] btKey = Encoding.UTF8.GetBytes(key);

                byte[] btIV = Encoding.UTF8.GetBytes(iv);

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                using (MemoryStream ms = new MemoryStream())
                {
                    byte[] inData = Encoding.UTF8.GetBytes(sourceString);
                    try
                    {
                        using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))
                        {
                            cs.Write(inData, 0, inData.Length);

                            cs.FlushFinalBlock();
                        }

                        return Convert.ToBase64String(ms.ToArray());
                    }
                    catch
                    {
                        return sourceString;
                    }
                }
            }
            catch { }

            return sourceString;
        }

        /// <summary>
        /// 解密字符串
        /// </summary>
        public string Decrypt(string encryptedString, string key, string iv)
        {
            byte[] btKey = Encoding.UTF8.GetBytes(key);

            byte[] btIV = Encoding.UTF8.GetBytes(iv);

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            using (MemoryStream ms = new MemoryStream())
            {
                byte[] inData = Convert.FromBase64String(encryptedString);
                try
                {
                    using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
                    {
                        cs.Write(inData, 0, inData.Length);

                        cs.FlushFinalBlock();
                    }

                    return Encoding.UTF8.GetString(ms.ToArray());
                }
                catch
                {
                    return encryptedString;
                }
            }
        }
    }
}

Call:

    class Program
    {
        static void Main(string[] args)
        {
            User user = new User("yangyoushan", "000000");

            Console.WriteLine(string.Format("用户名:{0}", user.UserName));

            Console.WriteLine(string.Format("加密后的密码:{0}", user.UserEncryptPassword));

            Console.WriteLine(string.Format("明文的密码:{0}", user.UserDecryptPassword));

            Console.ReadKey();
        }
    }

Result:

There are two problems in the code implemented by these two classes.
1. For every user instantiated,

            DES des = new DES();

            this.userEncryptPassword = des.Encrypt(userPassword, key, ivalue);

must be run, that is, a DES instance must be instantiated every time. This is not good. DES is instantiated just to call its methods, but it is inconvenient to instantiate it every time a method is called, and it also increases memory consumption.
2. For

        //加密解密用到的Key
        private string key = "20120719";
        //加密解密用到的向量
        private string ivalue = "12345678";

these two variables are used by every user instance and will not change. However, space must be allocated every time a user is instantiated, which also consumes memory, and is not very reasonable in terms of object-oriented thinking.

In this case, it is best to share the two methods of DES and call them directly without instantiation. For example, all methods of Math (Math.Abs(1);). Another is to set the key and ivalue variables in User to public, and they can also be accessed directly, and the memory space is only allocated once, and there is no need to allocate it separately when instantiating the user.
This requires the use of static, that is, the static keyword. The so-called static means that members are shared by a class. In other words, members declared as static do not belong to objects of a specific class, but belong to all objects of this class. All members of a class can be declared static, and can declare static fields, static properties, or static methods. But here we need to distinguish between const and static. Const means that the value of a constant cannot be changed during the running of the program, while static can change the value during running. If it is changed in one place, the changed value will be accessed in other places.
In this way, you can use static to optimize the above code, as follows:

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace YYS.CSharpStudy.MainConsole.Static
{
    /// <summary>
    /// 用户类
    /// </summary>
    public class User
    {
        //加密解密用到的Key
        private static string key = "20120719";
        //加密解密用到的向量
        private static string ivalue = "12345678";

        private string userName;

        private string userEncryptPassword;

        private string userDecryptPassword;

        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName
        {
            get
            {
                return userName;
            }
        }
        /// <summary>
        /// 用户密码,加密后的密码
        /// </summary>
        public string UserEncryptPassword
        {
            get
            {
                return userEncryptPassword;
            }
        }
        /// <summary>
        /// 用户密码,解密后的密码
        /// </summary>
        public string UserDecryptPassword
        {
            get
            {
                //使用静态方法和静态字段
                this.userDecryptPassword = DES.Decrypt(userEncryptPassword, key, ivalue);

                return userDecryptPassword;
            }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="userPassword"></param>
        public User(string userName, string userPassword)
        {
            this.userName = userName;

            this.userEncryptPassword = DES.Encrypt(userPassword, key, ivalue);
        }
    }

    /// <summary>
    /// 处理密码的类
    /// </summary>
    public class DES
    {
        /// <summary>
        /// 加密字符串
        /// </summary>
        public static string Encrypt(string sourceString, string key, string iv)
        {
            try
            {
                byte[] btKey = Encoding.UTF8.GetBytes(key);

                byte[] btIV = Encoding.UTF8.GetBytes(iv);

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                using (MemoryStream ms = new MemoryStream())
                {
                    byte[] inData = Encoding.UTF8.GetBytes(sourceString);
                    try
                    {
                        using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))
                        {
                            cs.Write(inData, 0, inData.Length);

                            cs.FlushFinalBlock();
                        }

                        return Convert.ToBase64String(ms.ToArray());
                    }
                    catch
                    {
                        return sourceString;
                    }
                }
            }
            catch { }

            return sourceString;
        }

        /// <summary>
        /// 解密字符串
        /// </summary>
        public static string Decrypt(string encryptedString, string key, string iv)
        {
            byte[] btKey = Encoding.UTF8.GetBytes(key);

            byte[] btIV = Encoding.UTF8.GetBytes(iv);

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            using (MemoryStream ms = new MemoryStream())
            {
                byte[] inData = Convert.FromBase64String(encryptedString);
                try
                {
                    using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
                    {
                        cs.Write(inData, 0, inData.Length);

                        cs.FlushFinalBlock();
                    }

                    return Encoding.UTF8.GetString(ms.ToArray());
                }
                catch
                {
                    return encryptedString;
                }
            }
        }
    }
}

Running results:

But there is one problem to note, the general method Static properties or static methods can be accessed outside the method. But if you want to access properties or methods outside the method in a static method, the properties and methods being accessed must also be static. Because general attributes or methods can only be used after allocating space after instantiation, while statically allocates memory space directly during compilation, so it is not possible to call other attributes or methods in static methods. , only static ones can be called at the same time.

The above is the compilation of C# basic knowledge: basic knowledge (10) static content. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing C# .NET Applications: Unit, Integration, and End-to-End TestingTesting C# .NET Applications: Unit, Integration, and End-to-End TestingApr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewAdvanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewApr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor