《Effective C#》Item 14:使用构造函数初始化语句

Effective C++与现代C++实践:从RAII到智能指针的编程哲学 在C++编程中,资源管理和内存安全是构建健壮系统的核心基础。RAII(Resource Acquisition Is Initialization)作为一种关键编程范式,通过将资源生命周期与对象绑定,从根本上解决了资源泄露问题。这一原理在现代C++中通过智能指针(如std::unique_ptr、std::shared_ptr)得到了优雅实现,它们不仅自动管理动态内存,还通过所有权语义确保了异常安全。这些技术对于开发高性能服务器、游戏引擎等对稳定性要求极高的应用场景至关重要。本文以《Effective C+ 阅读详情

在写程序的时候,往往会出现为一个类型提供不同场景的构造函数,可能大多构造函数比较相似,而C#中又不允许缺省参数,因此构造函数的编写无疑是一个重复工作。但是使用Copy和Paste来完成构造函数的编写,有时候很难达到统一,尤其是当成员发生变化的时候。因此比较常见的替换方法就是为构造函数提供一个统一的成员函数来完成初始化工作。

例如:

    public class MyClass

    {

        private int _Age;

        private string _Name;

 

        public MyClass( string Name)

        {

            InitMember( Name, 20 );

        }

 

        public MyClass( string Name, int Age )

        {

            InitMember( Name, Age );

        }

 

        /// <summary>

        /// Init class members

        /// </summary>

        /// <param name="Name"></param>

        /// <param name="Age"></param>

        private void InitMember( string Name, int Age )

        {

            _Age = Age;

            _Name = Name;

        }

    }

 

不过,在C#中提供了更为简明的方法,就是在构造函数初始化语句中调用另一构造函数,那么上面的形式可以改写为如下这样。

    public class MyClass

    {

        private int _Age;

        private string _Name;

 

        public MyClass( string Name):this( Name, 20 )

        {

        }

 

        public MyClass( string Name, int Age )

        {

            _Age = Age;

            _Name = Name;

        }

    }

 

对于这两者来说,执行效率没有太大差别,但从代码质量而言,后者要好很多,而且会使代码看起来更清晰。

 

其次,对于基类的调用。由于成员函数不能调用基类的构造函数,所以对于第一种编写就比较困难,后者就简单多了。

例如:

    public class MyClass:BaseClass

    {

        private int _Age;

        private string _Name;

 

        public MyClass( string Name):this( Name, 20 )

        {

        }

 

        public MyClass( string Name, int Age ):base( Name, Age )

        {

            _Age = Age;

            _Name = Name;

        }

    }

 

这里要提的一点就是构造函数初始化语句,对于“this”或者“base”之类的调用只能有一个,不能并存。

 

最后,就是对于readonly常量的初始化,由于readonly常量只能通过成员初始化语句或者在构造函数中被修改,因此在成员函数中无法修改readonly常量,这也是构造函数初始化语句要比成员函数好的重要一个因素。

 

有了上面的说明,对于两者的对比,可以形成如下这个简单的对比表。

 

效率

代码结构

基类调用

静态成员初始化

构造函数初始化语句

一样

简明清晰

容易

可以

成员函数

比较清晰

比较麻烦

不能

(注:这里不提倡Copy/Paste方法来重复编写构造函数)

 
C#关于构造函数初始化器的使用 有时,在一个类中有几个构造函数,以容纳某些可选参数,这些构造函数都包含一些共同的代码。   例如,下面的情况: class Car { private string description; private uint nWheels; public Car(string model, uint nWheels) { this.description = model; this.nWheels = nWheels; } public Car(string description) { this.description = description; this.nWheel 立即下载

相关推荐

ChromeOS安装教程

ChromeOS,是基于Linux内核研发的ChromiumOS开源系统的闭源系统,最大的特色就是内置了Chrome浏览器,早期主要以Web云端应用程序为主,后来逐渐引入了Android子系统和Linux子系统。本文主要简述摸索的家用笔记本安装ChromeOS安装方法,供各位玩机朋友参考。

weixin_45751495的博客 8114

《随笔一》——C#中的“静态构造函数、对象初始化语句”

目录 静态构造函数 对象初始化语句 静态构造函数 我们在使用类中的静态成员时,先要初始化这些成员。 在声明静态成员时、可以同时提供一个初始值。 但有时候我们需要执行更复杂的初始化操作, 这应该怎么办呢? 我们可以把构造函数声明成static的, 一般来说, 静态的构造函数初始化类的静态字段。 关于静态构造函数应注意的有: 那么一个类只能有一个静态构造函数,而且不能带参数、没有返回...

TAOTAO 968

告别Sourceforge安装器!手把手教你下载MinGW-w64离线包并配置环境变量(Windows 10/11)

本文详细介绍了如何在Windows 10/11系统上通过下载MinGW-w64离线包并配置环境变量,完全绕过Sourceforge安装器的问题。从选择正确的版本、解压到本地目录,到设置系统环境变量和验证编译环境,手把手指导开发者快速搭建稳定的GCC编译环境,解决常见的安装困扰。

weixin_30896825的博客 336

C#箴言:使用构造函数初始化语句

在写程序的时候,往往会出现为一个类型提供不同场景的构造函数,可能大多构造函数比较相似,而C#中又不允许缺省参数,因此构造函数的编写无疑是一个重复工作。但是使用Copy和Paste来完成构造函数的编写,有时候很难达到统一,尤其是当成员发生变化的时候。因此比较常见的替换方法就是为构造函数提供一个统一的成员函数来完成初始化工作。   例如: public class MyClass

_ A p r i l °__ 793

嵌入式系统中的轻量级压缩实践——miniLZO在STM32上的性能优化

本文深入探讨了miniLZO轻量级压缩算法在STM32嵌入式系统中的性能优化实践。通过对比无损压缩算法的性能特点,详细解析了miniLZO在内存占用、压缩速度方面的优势,并提供了STM32移植、参数调优及创新应用案例,帮助开发者在资源受限环境中实现高效数据压缩。

weixin_30776273的博客 84

【AUCell打分】:评估一个基因集在单细胞转录组的每个细胞中特定的活性程度

AUCell使用曲线下面积来计算输入基因集的一个有意义的基因子集是否在每个细胞的表达基因中富集。AUC 分数在所有细胞中的分布允许探索特征的相对表达。由于评分方法是基于排名的,因此 AUCell 与基因表达单位和归一化程序无关。此外,由于细胞是单独评估的,因此可以很容易地应用于更大的数据集。

weixin_40695088的博客 1万+

C#构造函数与初始化列表

1 // Namespace Declaration 2 using System; 3 4 // helper class 5 class OutputClass 6 { 7 string myString; 8 9 // Constructor 10 public OutputClass(string inputString)...

weixin_34149796的博客 2344

配置某VLAN下ONU的二层互访(隔离)问题(解决OLT二层隔离问题)

问题:OLT的ONU节点之间在同一VLAN下的终端默认隔离,在确实需要互通的场景下如何解决。

symstandsun的博客 4567

C# 结构体的构造函数与初始化

     C#中结构都有一个默认的不带参数的构造函数, 用于对结构的字段进行初始化,并且结构的默认构造函数不能被重写。     C#结构体构造函数之中定义的数组还可以通过构造函数传参数进行初始化操作!     1和2的作用相同,但是用2的方式定义的话需要选中 “项目属性/生成/允许不安全代码"。     以下是来自MSDN     结构与类共享大多数相同的语法,但结构比类受到的限制

站在巨人的肩膀上 1万+

vue支付项目-APP支付宝支付功能

如果用户已安装支付宝客户端,商家 App 唤起支付宝完成支付,支付完后跳回到商家 App 内,最后展示支付结果。如果用户没有安装支付宝客户端,商家 App 内会调起支付宝网页支付收银台,用户登录支付宝账号,支付完后展示支付结果。1.点击按钮开通或者续费,会验证是否选择会员商品以及对协议是否查看选中(这里根据项目需要自行验证,可忽略),验证通过打开选择支付方式弹窗页面,选择微信支付或者支付宝支付;4.可取消支付,放弃支付会返回会员页面,页面提示支付取消;1.判断支付方式,如果是2,则是支付宝支付方式。

总结前端开发中遇到的问题,分享前端知识 1万+

单片机:实现简单的时间片轮询调度(附完整源码)

单片机:实现简单的时间片轮询调度(附完整源码)

希望我的博客,能帮上你解决学习中工作中所遇到的问题 384

[转载]《Effective C#》Item 14:使用构造函数初始化语句

《Effective C#》Item 14:使用构造函数初始化语句《Effective C#》Item 14:使用构造函数初始化语句 在写程序的时候,往往会出现为一个类型提供不同场景的构造函数,可能大多构造函数比较相...

congji3817的博客 145

遥感图像地物覆盖分类,数据集制作-分类模型对比-分类保姆级教程

1.新建shp文件地理坐标系保持和影像一致,面类型2.打开属性表3.添加字段这里分类6类,点击添加值添加添加完毕开始人工选地物类型,制作数据集开始标注,标注的时候可以借助谷歌地图来看标记足够多的样本打开面转栅格工具设置nodata值为15。

热爱分享,热爱记录 2525

Effective C# Item14: Utilize Constructor Chaining

Effective C# Item14: Utilize Constructor Chaining 当我们写类的构造函数的时候经常会有许多种重载版本,它们完成的工作有一部分是重复的。许多开发者往往是先写第一个构造函数,然后拷贝粘贴它们到其他的构造函数当中去。我们应当停止这种做法。当我们发现许多重载的构造函数都包含有一些普遍的算法时,我们应当将这些逻辑集合到构造函数中,形成构...

aijinyao5713的博客 135

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Effective C# Item14:利用构造器链

编写构造函数通常是一件重复性的劳动,我们经常需要在不同声明形式的构造函数中,对同一个成员变量进行同样的初始化操作,为了完成这个任务,通常有以下三种方式。 对代码采用“复制/粘贴”的方式,在写好一个构造函数后,将代码粘贴到其他构造函数中。 采用辅助函数的方式,将共通的逻辑放置到一个单独的方法中,然后在每个构造函数中调用这个方法。 采用构造器链的方式,在一个构造函数中,使用另外的构造

尹自强.DoSomething() 470

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

Effective C# Item13:使用静态构造器初始化静态类成员

    在创建类型的任何实例之前,我们需要初始化这个类型中的静态成员变量,C#可以通过静态初始化器或者静态构造函数来完成这个任务,其中静态构造器是一个特殊的函数,它会在一个类的任何方法、变零或者属性被访问之前执行。     我们不应该使用类型的示例构造函数或者类型中的某些非静态方法来初始化类型的静态成员变量。     如果静态成员初始化的过程不复杂,那么我们可以在类型的初始化器中对其进行初始化...

weixin_34378969的博客 130

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

Item 2: Prefer readonly to const(Effective C#)

  Compile-time constants are limited to numbers and strings. Read-onlyvalues are also constants, in that they cannot be modified after the constructorhas executed.  You can use readonly values for i...

weixin_30823833的博客 103

Item 14: Minimize Duplicate Initialization Logic(Effective C#)

  Here is theorder of operations for constructing the first instance of a type:  1. Static variable storage is set to 0.  2. Static variable initializers execute.  3. Static constructors for the base...

weixin_30278237的博客 128

Effective C# Item8:确保0是值类型的有效状态

    .NET会将对象的值默认设置为0,对于值类型来说,例如struct,我们无法阻止开发人员将结构体中的成员设置为0,因此,我们需要将0设置为有效状态。     对于枚举类型来说,如果通过new的方式新建一个枚举类型的对象,那么对象的值是0,代码如下。 代码 1 public enum EnumSex 2 { 3 Female = 1, 4 ...

weixin_34025051的博客 120
上一篇: 《Effective C#》Item 13:使用静态构造函数初始化静态成员
下一篇: 《Effective C#》Item 15:利用using和try-finally来释放资源
Knight94
博客等级 码龄25年 1013粉丝 87原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值