这是我的类,它启动Wireshark
进程并返回文件详细信息:
public class Capinfos
{
private int _packets;
private string _duration;
private void getPackets(string file)
{
///
}
private void getDuration(string file)
{
///
}
public int packets
{
get { return _packets; }
}
public string duration
{
get { return _duration; }
}
public Capinfos getFileDetails(string file)
{
this.getNumberOfPackets(file);
this.getFileDuration(file);
return this;
}
}
主要
Capinfos capinfos = new Capinfos();
Capinfos cap = capinfos.getFileDetails(file);
我的问题是关于getFileDetails
函数,以这种方式返回我的对象是否可以?
答案 0 :(得分:3)
为什么要参考你已有的东西。如上所述,您可以使用构造函数传递您需要的信息来构建'你的班级:
public class Capinfos
{
private int _packets;
private string _duration;
//constructor;
public Capinfos(string file)
{
this.getPackets(file);
this.getDuration(file);
}
private int getPackets(string file)
{
///
}
private string getDuration(string file)
{
///
}
public int packets
{
get { return _packets; }
}
public string duration
{
get { return _duration; }
}
}
主:
Capinfos capinfos = new Capinfos(file);
答案 1 :(得分:2)
您还可以将getFilesDetails
方法实现为静态工厂方法
public class Capinfos
{
private int _packets;
private string _duration;
private void getPackets(string file)
{
///
}
private void getDuration(string file)
{
///
}
public int packets
{
get { return _packets; }
}
public string duration
{
get { return _duration; }
}
public static Capinfos GetFileDetails(string file)
{
var info = new Capinfos(file); //allowed, because it's the same class
info.getNumberOfPackets(file);
info.getFileDuration(file);
return info;
}
}
使用
var cap = Capinfos.GetFileDetails(file);
答案 2 :(得分:1)
我实际上将该文件作为构造函数。您没有像StringBuilder
那样使用构建器模式,因此返回相同的引用很奇怪。
答案 3 :(得分:0)
我建议a)为您的数据创建只读struc
,b)将文件中的读取函数组合
public struct CapInfo
{
public readonly int Packets;
public readonly string Duration;
CapInfo(int packets, string duration)
{
this.Packets=packets;
this.Duration=duration;
}
public static CapInfo ReadFileDetails(string file)
{
using(var fs=System.IO.File.Open(file, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
int packets = // from the file
string duration = // from the file
return new CapInfo(packets, duration);
}
}
}
class Program
{
static void Main(string[] args)
{
var info=CapInfo.ReadFileDetails(file);
}
}