当前位置:网站首页>C # basic knowledge (2)
C # basic knowledge (2)
2022-07-03 23:06:00 【BeanInJ】
List of articles
Write it at the front
Judge 、 loop 、 Construction method 、 Method overloading, etc , and java The language is basically similar to .
C# Medium goto、 Destructor 、readonly Read only objects 、partial Part of the class is java Not found in .
1、 Judgment and circulation
break Used to interrupt the loop
continue Skip this cycle
if…else
class Program
{
static void Main(string[] args)
{
Console.WriteLine(" Please enter an integer :");
// Convert the value entered from the console to int type
int num = int.Parse(Console.ReadLine());
if (num % 2 == 0)
{
Console.WriteLine(num+" yes 2 Multiple !");
}else if(num % 3 == 0){
Console.WriteLine(num+" yes 3 Multiple !");
}
else
{
Console.WriteLine(num+" No 2 or 3 Multiple !");
}
}
}
switch…case
class Program
{
static void Main(string[] args)
{
Console.WriteLine(" Please enter the grade (0~100 The integer of )");
int points = int.Parse(Console.ReadLine());
switch (points / 10)
{
case 10:
Console.WriteLine(" good ");
break;
case 9:
Console.WriteLine(" pass ");
break;
default:
Console.WriteLine(" fail, ");
break;
}
}
}
If case 10 and case 9 The output content is the same , You can do something like this
class Program
{
static void Main(string[] args)
{
Console.WriteLine(" Please enter the student's test score (0~100 The integer of )");
int points = int.Parse(Console.ReadLine());
if(points < 0 || points > 100)
{
points = 0;
}
switch (points / 10)
{
case 10:
case 9:
Console.WriteLine(" good ");
break;
case 8:
Console.WriteLine(" good ");
break;
case 7:
case 6:
Console.WriteLine(" pass ");
break;
default:
Console.WriteLine(" fail, ");
break;
}
}
}
for
class Program
{
static void Main(string[] args)
{
// Set the variables for storing and
int sum = 0;
for(int i = 1; i <= 10; i++)
{
Console.WriteLine(i);
sum += i;
}
Console.WriteLine("1~10 And for :" + sum);
}
}
while
class Program
{
static void Main(string[] args)
{
int i = 1;
int sum = 0;// Deposit 1~10 And
while (i <= 10)
{
sum = sum + i;
Console.WriteLine(i);
i++;
}
Console.WriteLine("1~10 And for :" + sum);
}
}
do while
class Program
{
static void Main(string[] args)
{
int i = 1;
do
{
Console.WriteLine(i);
i++;
} while (i <= 10);
}
}
goto
class Program
{
static void Main(string[] args)
{
int count = 1;
login:
Console.WriteLine(" Please enter a user name ");
string username = Console.ReadLine();
Console.WriteLine(" Please input a password ");
string userpwd = Console.ReadLine();
if (username == "aaa" && userpwd == "123")
{
Console.WriteLine(" Login successful ");
}
else
{
count++;
if (count > 3)
{
Console.WriteLine(" Too many user name or password errors ! sign out !");
}
else
{
Console.WriteLine(" Wrong user name or password ");
goto login;// return login Re enter the user name and password at the label
}
}
}
}
2、 class 、 object 、 Method
There can be multiple classes in a namespace
using System;
namespace code_1
{
class Test
{
}
class Test1
{
}
}
The concrete syntax form of class definition is as follows .
Class access modifier Modifier Class name
{
Class members
}
among :
- Class access modifier : Used to set access restrictions on classes , Include public、internal Or don't write , use internal Or not writing means that the class can only be accessed in the current project ;public Represents that the class can be accessed in any project .
- Modifier : A modifier is a description of the characteristics of a class itself , Include abstract、sealed and static.abstract It means Abstract , Classes that use its modifier cannot be instantiated ;sealed The decorated class is the sealed class , You can't Be inherited ;static The decorated class is a static class , Can't be instantiated .
- Class name : The class name is used to describe the function of a class , Therefore, it is better to have practical significance when defining class names , This makes it easy for users to understand the content described in the class . Class names must be unique in the same namespace .
Class members : Elements that can be defined in a class , It mainly includes fields 、 attribute 、 Method .
After the field is defined in the class , When the class loads , The field will be automatically assigned .
namespace code_1
{
class Test
{
private int id; // Define private integer fields id, Automatic assignment 0
public readonly string name; // Define public read-only string type fields name, Automatically assign a null value
internal static int age; // Define internal static integer fields age, Automatic assignment 0
private const string major = " Computer "; // Define private string type constants major, There is an initial value
}
}
2.1、readonly Read only objects
stay C# There are several key points in using read-only fields :
(1) Read only fields can be assigned together in the definition or in the structural method of the class ;
(2) In addition to the structural approach , The value of the read-only field cannot be modified elsewhere ;
(3) The characteristics of read-only fields can only be get accessor , Can not have set, It's obvious ;
2.2、const Constant
const Constants can only be initialized together with declarations ( assignment ).
readonly Fields can be initialized in declaration or structure functions .
2.3、internal Internal object
internal( Inside ): The limitation is that it can only be accessed in the same assembly , Can cross class
2.4、static Static objects
There is only one static object , All static members are created in the “ Static storage area ” Inside , Once created, until the program exits , To be recycled .
2.4、get、set accessor
namespace code_1
{
class Book
{
private int id;
private string name;
private double price;
private String desc;
public int Id
{
get
{
return id;
}
set
{
id = value;
}
}
// It can also be abbreviated in this way
public string Name{
get; set;}
// Read only form
public double price{
get;}=10.5;
// If you do not allow other classes to access property values
public String desc{
private get; set;}
}
}
2.5、 Calling class members
class Book
{
public int Id {
get; set; }
public string Name {
get; set; }
public double Price {
get; set; }
public void PrintMsg()
{
Console.WriteLine(" Book number :" + Id);
Console.WriteLine(" The name of the book :" + Name);
Console.WriteLine(" The book price :" + Price);
}
}
class Program
{
static void Main(string[] args)
{
Book book = new Book();
// Assign values to properties
book.Id = 1;
book.Name = " Fundamentals of computer ";
book.Price = 34.5;
book.PrintMsg();
}
}
take Book The properties and methods in the class are changed to static
class Book
{
public static int Id {
get; set; }
public static string Name {
get; set; }
public static double Price {
get; set; }
public static void SetBook(int id, string name, double price)
{
Id = id;
Name = name;
Price = price;
}
public static void PrintMsg()
{
Console.WriteLine(" Book number :" + Id);
Console.WriteLine(" The name of the book :" + Name);
Console.WriteLine(" The book price :" + Price);
}
}
class Program
{
static void Main(string[] args)
{
Book.SetBook(1, " Fundamentals of computer ", 34.5);
Book.PrintMsg();
}
}
2.6、 Constructors
Constructors are used to execute when creating objects of classes
class User
{
// The constructor with the same name as the class
public User(string name, string password, string tel)
{
this.Name = name;
this.Password = password;
this.Tel = tel;
}
public string Name {
get; set; }
public string Password {
get; set; }
public string Tel {
get; set; }
public void PrintMsg()
{
Console.WriteLine(" user name :" + this.Name);
Console.WriteLine(" The secret code :" + this.Password);
Console.WriteLine(" cell-phone number :" + this.Tel);
}
}
// Call the instance
class Program
{
static void Main(string[] args)
{
User user = new User(" Xiao Ming ","123456","13131351111");
user.PrintMsg();
}
}
2.7、 Destructor
Deconstruction method in garbage collection 、 Use when releasing resources . The destructor method is called after the class operation is completed .
// ~ Class name , It's a deconstruction method
~User()
{
Console.WriteLine(" The destruct method is called ");
}
2.8、lambda expression
class LambdaClass
{
public static int Add1(int a, int b) => a + b;
public static void Add2(int a, int b) => Console.WriteLine(a + b);
}
2.9、 Nested class
class OuterClass
{
public class InnerClass
{
public string CardId {
get; set; }
public string Password {
get; set; }
public void PrintMsg()
{
Console.WriteLine(" The card number is :" + CardId);
Console.WriteLine(" The password for :" + Password);
}
}
}
// Calls to nested classes
class Program
{
static void Main(string[] args)
{
OuterClass.InnerClass outInner = new OuterClass.InnerClass();
outInner.CardId = "622211100";
outInner.Password = "123456";
outInner.PrintMsg();
}
}
2.10、partial Part of class
A class can consist of multiple parts , as follows
public partial class Course
{
public int Id {
get; set; }
public string Name {
get; set; }
public double Points {
get; set; }
}
public partial class Course
{
public void PrintCoures()
{
Console.WriteLine(" Course number :" + Id);
Console.WriteLine(" Course name :" + Name);
Console.WriteLine(" course credit :" + Points);
}
}
partial It can also be used to modify methods ,
Some methods should be noted as follows 3 spot :
- Some methods must be private , And can't use virtual、abstract、override、new、sealed、extern Equal modifier .
- Some methods cannot have a return value .
- Cannot be used in some methods out Parameters of type .
public partial class Course
{
public int Id {
get; set; }
public string Name {
get; set; }
public double Points {
get; set; }
partial void PrintCourse();
// call PrintCourse Method
public void PrintMsg()
{
PrintCourse();
}
}
public partial class Course
{
public void PrintCoures()
{
Console.WriteLine(" Course number :" + Id);
Console.WriteLine(" Course name :" + Name);
Console.WriteLine(" course credit :" + Points);
}
}
边栏推荐
- Unique in China! Alibaba cloud container service enters the Forrester leader quadrant
- BUUCTF,Misc:LSB
- [note] glide process and source code analysis
- Yyds dry goods inventory Spring Festival "make" your own fireworks
- 540. Single element in ordered array
- Get current JVM data
- Qtoolbutton available signal
- Recursive least square adjustment
- IDENTITY
- Xiangong intelligent obtained hundreds of millions of yuan of b-round financing to accelerate the process of building non-standard solutions with standardized products
猜你喜欢
Harbor integrated LDAP authentication
How to quickly build high availability of service discovery
Loop compensation - explanation and calculation of first-order, second-order and op amp compensation
Team collaborative combat penetration tool CS artifact cobalt strike
Qtoolbutton available signal
Pyqt5 sensitive word detection tool production, operator's Gospel
webAssembly
Buuctf, misc: n solutions
Pooling idea: string constant pool, thread pool, database connection pool
3 environment construction -standalone
随机推荐
Is the controller a single instance or multiple instances? How to ensure the safety of concurrency
Pyqt5 sensitive word detection tool production, operator's Gospel
Hcip 13th day notes
2022.02.14
Subset enumeration method
Common problems in multi-threaded learning (I) ArrayList under high concurrency and weird hasmap under concurrency
[sg function] 2021 Niuke winter vacation training camp 6 h. winter messenger 2
2 spark environment setup local
Pooling idea: string constant pool, thread pool, database connection pool
Buuctf, web:[geek challenge 2019] buyflag
A preliminary study on the middleware of script Downloader
BUUCTF,Misc:LSB
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
Yyds dry goods inventory hands-on teach you to create a jigsaw puzzle using the canvasapi
Blue Bridge Cup -- guess age
ThreadLocal function, scene and principle
Blue Bridge Cup -- Mason prime
Mindmanager2022 serial number key decompression installer tutorial
[Android reverse] use DB browser to view and modify SQLite database (download DB browser installation package | install DB browser tool)
Hcip day 15 notes