从另一个调用一个构造函数
我有两个构造函数,它们将值提供给只读字段。
public class Sample
{public Sample(string theIntAsString){int i = int.Parse(theIntAsString);_intField = i;}public Sample(int theInt) => _intField = theInt;public int IntProperty => _intField;private readonly int _intField;
}
一个构造函数直接接收值,另一个构造函数进行一些计算并获得值,然后设置字段。
现在这是要抓住的地方:
- 我不想重复设置代码。 在这种情况下,只设置了一个字段,但是当然可能不止一个。
- 要使这些字段为只读,我需要从构造函数中进行设置,因此无法将共享代码“提取”到实用程序函数中。
- 我不知道如何从另一个调用一个构造函数。
有任何想法吗?
#1楼
我正在改进超级猫的答案。 我猜也可以做到以下几点:
class Sample
{private readonly int _intField;public int IntProperty{get { return _intField; }}void setupStuff(ref int intField, int newValue){//Do some stuff here based upon the necessary initialized variables.intField = newValue;}public Sample(string theIntAsString, bool? doStuff = true){//Initialization of some necessary variables.//==========================================int i = int.Parse(theIntAsString);// ................// .......................//==========================================if (!doStuff.HasValue || doStuff.Value == true)setupStuff(ref _intField,i);}public Sample(int theInt): this(theInt, false) //"false" param to avoid setupStuff() being called two times{setupStuff(ref _intField, theInt);}
}
#2楼
这是一个示例,该示例调用另一个构造函数,然后检查其设置的属性。
public SomeClass(int i){I = i;}public SomeClass(SomeOtherClass soc): this(soc.J){if (I==0){I = DoSomethingHere();}}
#3楼
当从基类继承一个类时,可以通过实例化派生类来调用基类构造函数
class sample
{public int x;public sample(int value){x = value;}
}class der : sample
{public int a;public int b;public der(int value1,int value2) : base(50){a = value1;b = value2;}
}class run
{public static void Main(string[] args){der obj = new der(10,20);System.Console.WriteLine(obj.x);System.Console.WriteLine(obj.a);System.Console.WriteLine(obj.b);}
}
示例程序的输出是
50 10 20
您还可以使用this
关键字从另一个构造函数调用一个构造函数
class sample
{public int x;public sample(int value) {x = value;}public sample(sample obj) : this(obj.x) {}
}class run
{public static void Main(string[] args) {sample s = new sample(20);sample ss = new sample(s);System.Console.WriteLine(ss.x);}
}
该示例程序的输出是
20
#4楼
是的,您可以在调用基础或此方法之前调用其他方法!
public class MyException : Exception
{public MyException(int number) : base(ConvertToString(number)) {}private static string ConvertToString(int number) { return number.toString()}}
#5楼
像这样:
public Sample(string str) : this(int.Parse(str)) { }
#6楼
在构造函数的主体之前,请使用以下任一方法:
: base (parameters): this (parameters)
例:
public class People: User
{public People (int EmpID) : base (EmpID){// Add more statements here.}
}
#7楼
构造函数链接,即当您要在单个调用中调用多个构造函数时,可以将“基础”用于“关系”,而可以将“ This”用于同一类。
class BaseClass
{public BaseClass():this(10){}public BaseClass(int val){}
}class Program{static void Main(string[] args){new BaseClass();ReadLine();}}
#8楼
错误处理和使代码可重用是关键。 我将字符串添加到int验证中,并且可以根据需要添加其他类型。 使用更可重用的解决方案解决此问题的方法可能是:
public class Sample
{public Sample(object inputToInt){_intField = objectToInt(inputToInt);}public int IntProperty => _intField;private readonly int _intField;
}public static int objectToInt(object inputToInt)
{switch (inputToInt){case int inputInt:return inputInt;break;case string inputString:if (!int.TryParse(inputString, out int parsedInt)){throw new InvalidParameterException($"The input {inputString} could not be parsed to string");}return parsedInt;default:throw new InvalidParameterException($"Constructor do not support {inputToInt.GetType().Name}");break;}
}
#9楼
如果在没有自己的方法的初始化的情况下不能令人满意地实现您想要的结果(例如,因为您想在初始化代码之前做太多事情,或者将其包装在try-finally中,等等),您可以拥有任何或全部构造函数通过引用初始化例程传递只读变量,然后该初始化例程将能够随意操作它们。
public class Sample
{private readonly int _intField;public int IntProperty => _intField; private void setupStuff(ref int intField, int newValue) => intField = newValue;public Sample(string theIntAsString){int i = int.Parse(theIntAsString);setupStuff(ref _intField,i);}public Sample(int theInt) => setupStuff(ref _intField, theInt);
}
从另一个调用一个构造函数相关推荐
- 利用类定义一个指针会调用默认构造函数吗_C++的拷贝构造函数
拷贝构造函数是一种特殊的构造函数,它在创建对象时,是使用同一类中之前创建的对象来初始化新创建的对象.拷贝构造函数通常用于: 通过使用另一个同类型的对象来初始化新创建的对象. 复制对象把它作为参数传递给 ...
- java 调用其他构造函数_我如何在Java中调用另一个构造函数?
是的,这是可能的: public class Foo { private int x; public Foo() { this(1); } public Foo(int x) { this.x = x ...
- Java Bean 为什么必须要有一个无参构造函数?
JAVA EE 中,JavaBean 是一个很重要的概念,而 JavaBean 还有以下的使用习惯. 首先我们知道,有两种方法为java对象中的元素赋值: 1. 通过类的带参数构造函数的方法 2. 通 ...
- java构造函数有参无参_Java Bean 为什么必须要有一个无参构造函数
JAVAEE中,javaBean是一个很重要的概念 而JavaBean还有以下的使用习惯 首先我们知道,有两种方法为java对象中的元素赋值, 1. 通过类的带参数构造函数的方法 2. 通过类的set ...
- c语言指针指向字符串单个,C语言 有没有可能调用一个指向字符串的函数指针?...
我是个在学C的萌新,一天突发奇想,指令和数据只是对人来说才有意义, 一段二进制串对CPU来说既可是数据,也可是指令,IP指向哪里就当作指令执行.那这样的话是不是意味着可以在C中执行字符串呢? 可,在探 ...
- Mac idea使用Command + p 快捷键查看一个类的构造函数需要传入什么参数
Mac idea使用Command + p 快捷键查看一个类的构造函数需要传入什么参数 如下图所示
- jQuery以JSONP的访问调用一个WCF REST服务
JSONP(JSON with Padding)可以看成是JSON的一种"使用模式",用以解决"跨域访问"的问题. 下面是一个简单的例子用于模拟如何通过jQue ...
- 十分钟开发一个调用Activity的PhoneGap插件
在HybridApp开发中,非常多业务我们是没有办法通过HTML5+js实现的,比方调用第三方的包括Activity的jar包,一些必须使用原生代码才干实现的功能,比方复杂的UI的效果,调用通讯相关的 ...
- C++ Primer Plus P31 编程练习(调用一个用户自定义的函数(以光年值为参数,并返回对应天文单位的值)——中职
C++ Primer Plus P31 编程练习 第六题 编写一个程序,其main()调用一个用户自定义的函数(以光年值为参数,并返回对应天文单位的值).该程序按下面格式要求输入光年值,并显示结果: ...
最新文章
- Android 让EditText不可编辑
- ​CPU将进入新时代:押注计算芯片的极限协同设计
- 【小白的CFD之旅】20 计算区域的构建
- 白话Elasticsearch34-深入聚合数据分析之案例实战bucket嵌套实现颜色+品牌的多层下钻分析
- 【Opencv实战】“一岁年龄一岁心,匆匆岁月不由人“这款年龄检测机等你来(附源码)
- HDU - 4497 GCD and LCM
- 【第7篇】Python爬虫实战-收集gitee中的issue问题
- uva 11997(优先队列)
- 微软有“病”,推出bing,看上去算象个站内搜索,心寒!
- Advanced.MP3.WMA.Recorder.v5.8.WinAll-CAT
- vscode插件版本的选择与安装
- 智能电子秤全国产化电子元件推荐方案
- C语言打印输出图形(初版)
- 关于电的计算机公式,电功率计算公式大全
- 优酷kux文件转码成mp4
- lfs库下载_Git上传大文件夹LFS
- 肝移植笔记1:论文阅读-对率回归预测移植物失功概率
- 易福门电感式接近开关IGS200
- mysql数据库sa默认密码_SQL Server数据库sa密码相关问题的解决方法
- 初识Docker:(5)Docker自定义镜像