VS2005中的C#:如果一个类有两个构造函数,那么这些构造函数分享一些代码的最佳方法是什么?
例如.我怎么能避免在以下两个构造函数中使用x = 5和y = 10行:
public class MyObject {
int x;
int y;
int z;
public MyObject() {
x = 5;
y = 10;
}
public MyObject(int setZ) {
x = 5;
y = 10;
z = setZ;
}
Run Code Online (Sandbox Code Playgroud) 当我尝试使用APN构建内容时,我看到了这个代码块.有人可以解释一下,"这个"陈述是做什么的吗?
public ApplePushService(IPushChannelFactory pushChannelFactory, ApplePushChannelSettings channelSettings)
: this(pushChannelFactory, channelSettings, default(IPushServiceSettings))
Run Code Online (Sandbox Code Playgroud)
它是否像那些参数的默认值?
我目前有一个类,我对它的构造函数有点困惑.
public class BarListTracker : GotTickIndicator
{
public BarListTracker(BarInterval interval) : this(new BarInterval[] { interval }) { }
}
Run Code Online (Sandbox Code Playgroud)
这句话this(new BarInterval[] { interval })意味着什么?
我有2个构造函数,接受不同类型的参数:
public someClass(String s) {
// the string is parsed to an int array.
int[] array = doSomething(s);
this(array);
}
public someClass(int[] array) {
doSomethingElse(array);
}
Run Code Online (Sandbox Code Playgroud)
但是在第一个构造函数中,我得到"方法名称是预期的".有没有办法让构造函数在执行其他操作后调用另一个,或者它只是C#的限制?
我希望能够使用公共构造函数实现一个类,该构造函数默认调用私有构造函数,我认为它与下面的代码很接近,但事实并非如此.
public MySQLConnector()
: this MySQLConnector (ConfigurationManager.AppSettings["DBConnection"])
{
}
private MySQLConnector(string dbConnectionString)
{
//code
}
Run Code Online (Sandbox Code Playgroud) 假设我们有这两个结构......
public struct Example
{
public int Number { get; set; }
public Example(int Number)
{
Number = number;
}
}
Run Code Online (Sandbox Code Playgroud)
和:
public struct Example
{
public int Number { get; set; }
public Example(int number) : this()
{
Number = number;
}
}
Run Code Online (Sandbox Code Playgroud)
你可以看到有一个结构体,**this()**最后有一个构造函数,另一个没有。
两者有什么区别?
当我经常从Oracle数据库调用不同的数据集时,我使用了以下类来最小化代码重复.主要是我需要帮助来删除重载的构造函数中的代码重复,但任何其他建议也将不胜感激.
public class UniformData
{
private string connection = "My Connection String";
private OracleConnection con;
private OracleCommand com;
private OracleDataReader reader;
public UniformData(string sql)
{
con = new OracleConnection(connection);
con.Open();
com = new OracleCommand(sql, con);
}
public UniformData(string sql, List<SqlParameters> myParams)
{
con = new OracleConnection(connection);
con.Open();
com = new OracleCommand(sql, con);
foreach (SqlParameters Param in myParams)
{
com.Parameters.Add(Param.ParamName, Param.ParamValue);
}
}
public OracleDataReader GetReader()
{
reader = com.ExecuteReader();
return reader;
}
~UniformData()
{
con.Close();
con.Dispose();
com.Dispose();
reader.Close();
reader.Dispose();
} …Run Code Online (Sandbox Code Playgroud)