有没有办法让一个方法有多个实例?

时间:2014-06-27 15:34:47

标签: c# .net winforms

private void Extractions(string htmlFileName, int offLineFileNumber, bool onlineOffline)
        {
            if (onlineOffline == false)
            {
                OffLineDownload.offhtmlfiles();
                page = OffLineDownload.OffLineFiles[offLineFileNumber];
                byte[] bytes1 = File.ReadAllBytes(page);
                page = Encoding.GetEncoding(1255).GetString(bytes1);
                TextExtractor.GetDateTimeList(page);
                StreamWriter w = new StreamWriter(@"C:\Temp\" + htmlFileName);//@"d:\rotterhtml\rotterscoops.html");
                w.Write(page);
                w.Close();
                extractlinks.Links(@"C:\Temp\" + htmlFileName);
                TextExtractor.ExtractText(@"C:\Temp\" + htmlFileName, newText);
            }
            else
            {
                client.Encoding = System.Text.Encoding.GetEncoding(1255);
                page = client.DownloadString("http://rotter.net/scoopscache.html");
                TextExtractor.GetDateTimeList(page);
                StreamWriter w = new StreamWriter(@"d:\rotterhtml\rotterscoops.html");
                w.Write(page);
                w.Close();
                extractlinks.Links(@"d:\rotterhtml\rotterscoops.html");
                TextExtractor.ExtractText(@"d:\rotterhtml\rotterscoops.html", newText);
            }
        }

如果用户调用该方法,我希望他有两个选项可以使用所有3个变量调用它:

string htmlFileName, int offLineFileNumber, bool onlineOffline

或者在没有变量的情况下调用它,如果它是(),那么它将是自动的。

3 个答案:

答案 0 :(得分:2)

您可以使用可选参数来实现您的目标:

private void Extractions(string htmlFileName="", int offLineFileNumber=0, bool onlineOffline=true)
{
    // implementation
}

然后,您可以使用所需的参数调用您的方法,例如:

Extractions("myfile.txt", 1, true);  // or
Extractions("myfile.txt", 1)        

答案 1 :(得分:1)

您可以“重载”该方法。具有多个参数签名的同名。

private void Extractions()
{

}

由于你的方法是一个“无效”,我不知道你的意思是“if it's()所以它会自动为真。”

除非你的意思是:

private void Extractions(string htmlFileName, int offLineFileNumber)
{
     Extractions(htmlFileName, offLineFileNumber, true);
}

当然你也可以让offLine paremeter可选,并默认为true。

private void Extractions(string htmlFileName, int offLineFileNumber, bool onlineOffLine = true)
{
     ....
} 

答案 2 :(得分:0)

是的,它被称为方法重载。

只需使用不同的参数多次定义您的方法

private void Extractions(string htmlFileName, int offLineFileNumber, bool onlineOffline)
{
  //All your logic here
}

重载方法:

private void Extractions(string htmlFileName, int offLineFileNumber)
{
// Call the main method, passing true
Extractions(htmlFileName, offLineFileNumber, true);
}

见这里:http://csharpindepth.com/Articles/General/Overloading.aspx