3

这是我的班级,他们开始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功能的,以这种方式返回我的对象​​可以吗?

4

4 回答 4

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

于 2013-05-31T15:59:52.073 回答
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);
于 2013-05-31T15:57:53.163 回答
1

我实际上会将文件作为构造函数。您没有像 aStringBuilder那样使用构建器模式,因此返回相同的引用很奇怪。

于 2013-05-31T15:53:48.353 回答
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);
    }
}
于 2013-05-31T16:45:41.530 回答