Basic knowledge of C #: Fundamentals (10) static

Source: Internet
Author: User
Tags access properties decrypt
If you want to access a method or property of a class, be sure to instantiate the class first, and then use the class's object plus. Like what:
There is a user class and a class that handles passwords (encryption and decryption). After a user instance has not been generated, the password class is processed 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>///user class//</summary> public class Users {        Key private String key = "20120719" for encryption and decryption;        The vector private string ivalue = "12345678" for encryption and decryption;        private string UserName;        private string Userencryptpassword;        private string Userdecryptpassword;            <summary>///user name///</summary> public string UserName {get            {return userName; }}///<summary>//user password, encrypted password///</summary> public string USERENCRYPTP            Assword {get {return userencryptpassword; }}///<summary>//user password, decrypted password///</summary> public string userDecryptpassword {get {des des = new des (); This.userdecryptpassword = des.                Decrypt (Userencryptpassword, Key, Ivalue);            return Userdecryptpassword; }}///<summary>//constructor///</summary>//<param name= "UserName" > </param>//<param name= "UserPassword" ></param> public User (String userName, String userp            Assword) {this.username = UserName;            Des des = new des (); This.userencryptpassword = des.        Encrypt (UserPassword, Key, Ivalue);        }}///<summary>///Process password class///</summary> public class DES {//<summary>        Encrypted string///</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 (so                    urcestring); 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>//decryption string///</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 (encrypte                dstring); 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 ("user name: {0}", user. UserName));            Console.WriteLine (String. Format ("Encrypted password: {0}", user.) Userencryptpassword));            Console.WriteLine (String. Format ("Password for clear text: {0}", user.) Userdecryptpassword));            Console.readkey ();        }    }

Results:

There are two problems with the code implemented in these two classes.
1, for each instantiation of a user, to run

            Des des = new des ();            This.userencryptpassword = des. Encrypt (UserPassword, Key, Ivalue);

That is, each time you instantiate a des instance. It is not good to instantiate des just to invoke its method, but each invocation of the method has to be instantiated is not very convenient, but also increased memory consumption.
2, for

        Key        private String key = "20120719" for encryption and decryption;        The vector        private string ivalue = "12345678" for encryption and decryption;

These two variables are used by each user instance and do not change. But every instantiation of a user allocates space, which is also consumed internally, and is not reasonable in terms of object-oriented thinking.

In that case, it would be better to have the two methods of Des in common, and not be able to invoke them directly by instantiating them. For example, all methods of Math (Math.Abs (1);). Another is to set the user's key and Ivalue variables are also public, but also can be directly accessed, and allocate only one memory space, and the instantiation of the user no additional allocation.
This is going to use static, which is the static keyword. The so-called static is that members are shared by a class. That is, a member declared as static does not belong to an object of a particular class, and belongs to all objects of that class. Members of all classes can be declared as static and can declare static fields, static properties, or static methods. But there's a difference here. Const and Static,const are constants that cannot be changed in a program's operation, static can change values in the run, and a place is changed, and all other places have access to the changed values.
This allows the use of 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>///user class//</summary> public class Users {        Key private static string key = "20120719" for encryption and decryption;        The vector used to encrypt the decryption is private static string ivalue = "12345678";        private string UserName;        private string Userencryptpassword;        private string Userdecryptpassword;            <summary>///user name///</summary> public string UserName {get            {return userName; }}///<summary>//user password, encrypted password///</summary> public string USERENCRYPTP            Assword {get {return userencryptpassword; }}///<summary>//user password, decrypted password///</summary> PublIC string Userdecryptpassword {get {//Use static method and static field This.userde Cryptpassword = DES.                Decrypt (Userencryptpassword, Key, Ivalue);            return Userdecryptpassword; }}///<summary>//constructor///</summary>//<param name= "UserName" > </param>//<param name= "UserPassword" ></param> public User (String userName, String userp            Assword) {this.username = UserName; This.userencryptpassword = DES.        Encrypt (UserPassword, Key, Ivalue);        }}///<summary>///Process password class///</summary> public class DES {//<summary>         Encrypted string///</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 (so                    urcestring); 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>//Decrypt string///</summary> public static string Decrypt (String encry PtedsTring, 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 (encrypte                dstring); 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; }            }        }    }}

Operation Result:

Note, however, that a general method can access static properties or static methods outside of the method. However, if you are in a static method to access properties or methods outside the method, the properties and methods that are accessed must also be static. Because the general property or method is only allocated after the instantiation of space, can be used, and static is directly at compile time allocated memory space, so the static method calls other properties or methods are not allowed, can only invoke static at the same time.

The above is the basic knowledge of C #: Basic knowledge (10) static content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.