Table of Contents
string
Managed code and unmanaged code
StringBuilder
3、区别对待强转类型和as  is
Home Backend Development C#.Net Tutorial C# learning record: Writing high-quality code and improving organization suggestions 1-3

C# learning record: Writing high-quality code and improving organization suggestions 1-3

Aug 06, 2018 pm 02:54 PM
c#

Suggestion 1: Use strings correctly

string

string str1 = "str1" + 9;
string str2 = "str2" + 9.ToString();
Copy after login

The first line of code will generate a boxing and a string The concat

and the second line of code uses ToString(), which uses Number.FormatInt32

internally. Its prototype is

C# learning record: Writing high-quality code and improving organization suggestions 1-3

NumberFormatInt32 is an unmanaged method, and its operating efficiency is much higher than that of normal c# managed code, so the efficiency of the second line of code is higher than that of the first line

As for what is managed code and unmanaged code, I Quoting a passage from another blog:

Managed code and unmanaged code

As we all know, the high-level languages ​​we use for normal programming cannot recognized by the computer. High-level language needs to be translated into machine language before it can be understood and run by the machine.
In standard C/C, the compilation process is like this:
enter description here
The source code first goes through the preprocessor to parse the header files and macros, then goes through the compiler to generate assembly code, then goes through assembly to generate machine instructions, and finally connects all the files.
The advantage of this compilation method is that it ultimately directly generates machine code, which can be directly recognized and run by the computer without any intermediate running environment. However, the disadvantage is that because different platforms can recognize different machine codes, the program’s cross-platform capabilities Poor.
In the Java language, the source code is not directly translated into machine code, but compiled into an intermediate code (Bytecode). Therefore, running a Java program requires an additional JRE (Java Runtime Enviromental) running environment. There is a JVM (Java Virtual Machine, Java Virtual Machine) in the JRE. When the program is running, the intermediate code will be further explained is the machine code and runs on the machine.
The advantage of using intermediate code is that the program is more cross-platform and can be run on different devices once compiled.
Managed/unmanaged is a concept unique to Microsoft's .net framework, in which unmanaged code is also called native code. Similar to the mechanism in Java, the source code is first compiled into intermediate code (MSIL, Microsoft Intermediate Language), and then the CLR in .net compiles the intermediate code into machine code.
The difference between C# and Java is that Java is compiled first and then interpreted, while C# is compiled twice.
In addition to its cross-platform advantages, the hosting method also has a certain impact on the performance of the program. However, program performance is beyond the scope of this article and will not be discussed in detail here.
In addition, in .net, C can also be managed extended, so that C code also relies on .net and CLR to run, gaining the advantages of managed code.

简单理解就是托管代码加了一个中间层,使其可以跨平台,不过效率会降低,而非托管代码就不会产生这样的情况

所以我们编写代码秉承一个原则:尽量减少装箱拆箱

StringBuilder

StringBuilder的效率来源于预先以非托管的方式分配内存,如果没有预先定义长度,默认长度为16,不够的时候会重新分配内存,依次加16的倍数,所以如果你提前知道字符串需要的最大长度,最好预先定义好,这样就不会频繁分配内存从而带来效率的降低

2、使用默认转型方法

这个建议的大体内容是尽量使用系统所带的转换类型的方法

例如 int.Parse ToString() System.Convert 等等

3、区别对待强转类型和as is

两个类型之间转换有两种情况

1. 他们是父子类的关系: ChildType = (ChildType)ParentType

2.没有继承关系,或者继承同一个父类,这时候就需要重写强转方法

class FirstType
{
    public string Name { get; set; }
}

class SecondType
{
    public string Name { get; set; }
        
    public static explicit operator SecondType(FirstType firstType)
    {
        SecondType secondType = new SecondType() { Name = firstType.Name };
        return secondType;
    }
}

FirstType firstType = new FirstType() { Name = "张" };
SecondType secondType = (SecondType)firstType;
Copy after login

如果是继承的关系,为了效率推荐使用 ChildType = ParentType as ChildType

这个就更上面提到的,尽量使用系统方法的转换,而不是强制转换

我写Unity的时候有这样一个需求,右键点击装备的时候会使用,装备有Equipment,Weapon,我们需要判断是Equipment还是Weapon类型,它们都是继承Item类型,有两种方法可用:

Weapon weapon = item as Weapon;
if(weapon != null)
{
    //TODO 使用武器
}

if(item is Weapon)
{
    weapon weapon = item as Weapon;
    //TODO 使用武器
}
Copy after login

第一种方法只判断了一次类型,而第二种方法判断了两次类型

书上说as不能判断基元类型,但是经过我的测试发现书上写错了,as仅仅不能判断值类型,这里大家可以自己测试一下

C# learning record: Writing high-quality code and improving organization suggestions 1-3

C# learning record: Writing high-quality code and improving organization suggestions 1-3

相关文章:

C#学习记录:编写高质量代码改善整理建议4-8

C#学习记录:编写高质量代码改善整理建议9-15

The above is the detailed content of C# learning record: Writing high-quality code and improving organization suggestions 1-3. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1658
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
C# Serialization C# Serialization Sep 03, 2024 pm 03:30 PM

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

See all articles