C#支持控制台调用的窗体程序思路
首先,谁特么现在还用客户端小程序啊……/(ㄒoㄒ)/~~
【START】
这类程序有两种情况,如果在入口函数Main中没有传任何参数进来,那么就启动界面进行处理,如果传了参数并且验证无误,就启动控制台界面来处理。
为了形象地进行说明,这里就写一个小的虚构的项目。流程如下:
首先读取一个文件(源文件),然后复制其内容重复N次(N>=0),然后保存(目标文件)。
其中有这样几种情况:
1. N=0时,如果目标文件未指定,则清空源文件;否则创建空的目标文件。
2. N=1时,如果目标文件未指定,则不处理;否则复制源文件为目标文件。
3. N>1时,如果目标文件未指定,则更改源文件;否则更改目标文件。
创建每次转换所需参数的数据类:
public class ConvertInfo
{
public string InputFile { get; set; }
public string OutputFile { get; set; }
public uint Parameter { get; set; }
}
添加实例化方法(包括验证),然后合并到唯一构造函数中:
//"input" 0 "output"
//"input" 2
private void tryParse(string[] args)
{
try
{
if (args.Length < 2)
{
throw new ArgumentException(
"more parameters should be specified.");
}
System.IO.FileInfo input = new System.IO.FileInfo(args[0]);
if (!input.Exists)
{
throw new ArgumentException(
"invalid input file.");
}
this.InputFile = input.FullName;
int param = -1;
int.TryParse(args[1], out param);
if (param < 0)
{
throw new ArgumentException(
"invalid parameter.");
}
this.Parameter = (uint)param;
if (args.Length > 2)
{
System.IO.FileInfo output = new System.IO.FileInfo(args[2]);
if (output.FullName != input.FullName)
{
this.OutputFile = output.FullName;
}
}
}
catch
{
throw;
}
}
public ConvertInfo(params string[] args)
{
if (args == null)
{ //should not fire.