C#构造设计 [英] C# Constructor Design

查看:180
本文介绍了C#构造设计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有你的文件夹中传递类,然后将其熄灭并处理了很多指定的文件夹中的数据



例如:

  MyClass的MyClass的=新MyClass的(@C:\temp); 

现在它做什么它熄灭并读取说,一对夫妇一千文件,并用数据填充类。



我应该从构造出移动这个数据,并把它作为一个单独的方法,如:

  MyClass的MyClass的=新MyClass的(); 
myClass.LoadFromDirectory(@C:\temp);


解决方案

也许你应该尝试一下用静态方法这种方法。返回的对象的实例

  VAR MyClass的= MyClass.LoadFromDirectory(@C:\temp); 

这将保持初始化代码的构造之外,还有给你说,一线声明你正在寻找。






去的评论从下面的海报,通过增加国家的实现可以像这样:

 公共类MyClass的
{

#区域构造

公共MyClass的(字符串目录)
{
this.Directory =目录;
}

#endregion

#区域属性

公共MyClassState国家{获取;私人集;}

私人字符串_directory;

公共字符串目录
{
{返回_directory;}
私定
{
_directory =价值;
如果(string.IsNullOrEmpty(值))
this.State = MyClassState.Unknown;
,否则
this.State = MyClassState.Initialized;
}
}

#endregion



公共无效LoadFromDirectory()
{
如果(!this.State = MyClassState.Initialized || this.State = MyClassState.Loaded)
抛出新InvalidStateException();

//在载入

this.State = MyClassState.Loaded;
}

}

公共类InvalidStateException:异常{}


公共枚举MyClassState
{
未知,
初始化,
加载
}


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.

For instance:

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");

解决方案

Maybe you should try it this way with a static method that returns an instance of the object.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆