C#构造函数设计 [英] C# Constructor Design
问题描述
我有一个类,你在一个文件夹中传递,然后它关闭,并处理指定的文件夹内的很多数据。
I have a class which you pass in a folder and then it goes off and processes a lot of data within the specified folder.
例如:
MyClass myClass = new MyClass(@"C:\temp");
现在它做了什么,读取几千个文件,并填充数据。
Now what it does it goes off and reads say a couple thousand files and populates the class with data.
我应该将此数据从构造函数中移出,并将其作为一个独立的方法,如:
Should I move this data out from the constructor and have it as a seperate method, such as:
MyClass myClass = new MyClass();
myClass.LoadFromDirectory(@"C:\temp");
推荐答案
也许你应该用静态方法
var myClass = MyClass.LoadFromDirectory(@"C:\temp");
这会将初始化代码保留在构造函数之外,
This will keep the initialization code outside of your constructor, as well as giving you that "one line" declaration you are looking for.
从海报的下面的评论,通过添加状态一个实现可以像所以:
Going on the comment from below from the poster, by adding State an implementation could be like so:
public class MyClass
{
#region Constructors
public MyClass(string directory)
{
this.Directory = directory;
}
#endregion
#region Properties
public MyClassState State {get;private set;}
private string _directory;
public string Directory
{
get { return _directory;}
private set
{
_directory = value;
if (string.IsNullOrEmpty(value))
this.State = MyClassState.Unknown;
else
this.State = MyClassState.Initialized;
}
}
#endregion
public void LoadFromDirectory()
{
if (this.State != MyClassState.Initialized || this.State != MyClassState.Loaded)
throw new InvalidStateException();
// Do loading
this.State = MyClassState.Loaded;
}
}
public class InvalidStateException : Exception {}
public enum MyClassState
{
Unknown,
Initialized,
Loaded
}
这篇关于C#构造函数设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!