具有空主体和类似继承语法的构造函数有什么作用?
public class PhotoList : ObservableCollection<ImageFile>
{
public PhotoList() { }
**//this is the line that I dont recognise!!!!!!!!!!**
public PhotoList(string path) : this(new DirectoryInfo(path)) { }
public PhotoList(DirectoryInfo directory)
{
_directory = directory;
Update();
}
public string Path
{
set
{
_directory = new DirectoryInfo(value);
Update();
}
get { return _directory.FullName; }
}
public DirectoryInfo Directory
{
set
{
_directory = value;
Update();
}
get { return _directory; }
}
private void Update()
{
foreach (FileInfo f in _directory.GetFiles("*.jpg"))
{
Add(new ImageFile(f.FullName));
}
}
DirectoryInfo _directory;
}
public class PhotoList : ObservableCollection<ImageFile>
{
public PhotoList() { }
**//this is the line that I dont recognise!!!!!!!!!!**
public PhotoList(string path) : this(new DirectoryInfo(path)) { }
public PhotoList(DirectoryInfo directory)
{
_directory = directory;
Update();
}
public string Path
{
set
{
_directory = new DirectoryInfo(value);
Update();
}
get { return _directory.FullName; }
}
public DirectoryInfo Directory
{
set
{
_directory = value;
Update();
}
get { return _directory; }
}
private void Update()
{
foreach (FileInfo f in _directory.GetFiles("*.jpg"))
{
Add(new ImageFile(f.FullName));
}
}
DirectoryInfo _directory;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这称为构造函数链接 - 构造函数可以使用此语法调用同一类型中的其他构造函数(对同级构造函数使用
this
,对同级构造函数使用 < code>base 用于基本构造函数)。这是一个简单的示例,展示了它的工作原理:
输出:
This is called constructor chaining - constructors can call other constructors within the same type with this syntax (using
this
for sibling constructors andbase
for base constructors).Here is a simple example that shows how it works:
Output:
它调用类中以 DirectoryInfo 作为参数的另一个构造函数。
让我们看看如何使用这个类的调用者
It calls the other constructor in the class that takes a DirectoryInfo as argument.
Lets see how the caller of this class can be used
它使采用字符串参数的构造函数调用采用 DirectoryInfo 参数的构造函数,并将新的 DirectoryInfo 对象(该对象又使用字符串作为参数)传递给它。
我经常使用这种方法为复杂的类提供更简单的构造函数,让类本身使用默认值初始化属性,而不必重复初始化代码。
It makes the constructor that takes a string parameter invoke the constructor that takes a DirectoryInfo parameter, passing a new DirectoryInfo object (which in turn is using the string as parameter) to it.
I often use this approach to provide simpler constructors to complex classes, letting the class itself initializse properties with default values without having to duplicate intitiallization code.