search
HomeBackend DevelopmentC#.Net TutorialC# learning record: Writing high-quality code and improving organization suggestions 1-3

Suggestion 1: Use strings correctly

string

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

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;

如果是继承的关系,为了效率推荐使用 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 使用武器
}

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

书上说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
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
C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

Is C# Always Associated with .NET? Exploring AlternativesIs C# Always Associated with .NET? Exploring AlternativesMay 04, 2025 am 12:06 AM

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# vs. .NET: Clarifying the Key Differences and SimilaritiesC# vs. .NET: Clarifying the Key Differences and SimilaritiesMay 01, 2025 am 12:12 AM

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

Beyond the Hype: Assessing the Current Role of C# .NETBeyond the Hype: Assessing the Current Role of C# .NETApr 30, 2025 am 12:06 AM

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft