构造函数链接
我有以下代码:
public MapReader(string fName) {
FileName = fName;
}
public MapReader(){
Console.WriteLine("Input valid file name:");
string name = Console.ReadLine();
this(name);
}
显然这是 Java 方法,在 C# 中不起作用。是否有任何选项不需要添加初始化方法?
I have following code:
public MapReader(string fName) {
FileName = fName;
}
public MapReader(){
Console.WriteLine("Input valid file name:");
string name = Console.ReadLine();
this(name);
}
Apparently this is Java approach, which is not working in C#. Is there any option which doesn't need added method for initialization?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您无法在 C# 中执行此操作。您必须在另一个构造函数中设置该属性。
理想情况下,您应该分离出对控制台的依赖关系。
You can't do this in C#. You will have to set the property in the other constructor.
Ideally, you should separate out the dependency on the console.
在 C# 中你不能使用这种方法。
试试这个:
In C# you couldn' use that approach.
Try this:
尽管我同意其他人的观点,即对控制台的依赖对于此类来说可能不是最好的,但这是可行的:
Although I agree with others that having a dependency on the Console is probably not best for this class, this would work:
也许是这样的?
Maybe something like this?
您可以这样做:
You can to do so:
我不太喜欢这样的副作用构造函数的方法,你可以像这样模拟同样的事情:
I don't quite like the approach of having a side effecting constructor like that, you could simulate the same thing like this: