返回不同类型变量的方法 [英] A method returning different type of variables

查看:97
本文介绍了返回不同类型变量的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有以下代码:



  public  webSite4( double  bookPrice, string  titleBook, string  getUrl) //   bookamillion  
{
// 用于每次读取操作
byte [] buf = new byte [ 8192 ];

// 准备我们要求的网页
string urlResult = string .Empty;

if string .IsNullOrEmpty(isbnEntry.Text))
{
bookEntry.Text.Replace( +);
string urlTitle =
String .Format(
http://www.booksamillion.com/search?id=5910205702379&query= {0}& where = book_title& search .x = 24& search.y = 9& search = Search& affiliate =& sort = price_ascending
bookEntry.Text);
urlResult = urlTitle;

}
else if string .IsNullOrEmpty(bookEntry.Text))
{
string urlIsbn =
字符串 .Format(
http:// www。 booksamillion.com/search?id=5910205702379&query={0}&where=isbn&search.x=16&search.y=8&search=Search&affiliate=&sort=price_ascending
isbnEntry.Text);
urlResult = urlIsbn;
}
else
{
string urlBoth =
String .Format( http:/ /www.booksamillion.com/search?id=5910205702379&query={0}&where=isbn&search.x=16&search.y=8&search=Search&affiliate=&sort=price_ascending\"
isbnEntry.Text);
urlResult = urlBoth;
}

// 准备请求
CookieContainer cookies = new CookieContainer();
HttpWebRequest request =(HttpWebRequest)WebRequest.Create(urlResult);
HttpWebResponse response = null ;

// 设置标题值
request.Method = < span class =code-string>
GET;
request.CookieContainer = cookies;

// 获取响应数据
response =(HttpWebResponse) request.GetResponse();


string responseData = new StreamReader(response.GetResponseStream( ))ReadToEnd的();
response.Close();

string getPrice = string .Empty;

HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
htmlDoc.OptionFixNestedTags = true ;
htmlDoc.LoadHtml(responseData); // load html
HtmlAgilityPack.HtmlNode rootNode = htmlDoc.DocumentNode;

titleBook = rootNode.SelectSingleNode( / html / body / div [4] / div /div/div[2]/ol/li/div/span/a/img\").Attributes[ ALT]值。

getUrl = rootNode.SelectSingleNode( @ / html / body / div [4] / DIV / DIV / DIV [2] /醇/ LI / DIV /跨度/一个)InnerHtml.ToString();


getPrice = getPrice.Substring( 15 );


bookPrice = System.Convert.ToDouble(getPrice);

double priceConvert = bookPrice * 0 73 ; // 将USdollars转换为欧元

string webSource = BooksAMillion;
}

该方法基本上是从网站上获取数据(书名,价格和网址)。



想法是那样的我有3个具有相同变量的方法,需要比较所有bookPrice结果。这是通过为所有需要的方法提供返回类型并且能够将bookPrice变量放在一个地方并进行比较来完成的。



任何帮助都非常感谢:)



谢谢!

解决方案

我建​​议让该方法返回对象[] 。您可以根据需要处理从方法调用返回的每个项目。



方法签名看起来像这样:

 protected object [] ReturnMultipleTypes(object sender,EventArgs e)
{
object [] d = new object()[3];
返回d;
}



请记住,访问修饰符需要适合您的情况,并且数组的大小取决于您需要的项目数量返回。


如果要从方法中返回不同类型的多个值,但仍想使用强类型,那么使用元组是一种方法。示例:

  private   void  button1_Click( object  sender,EventArgs e)
{
var tt1 = method1( 一个 两个 100 .32D);

string title = tt1.Item1;
string bookURL = tt1.Item2;
double price = tt1.Item3;
}

私人元组<字符串,字符串,double> method1( string bookTitle, string bookURL, double bookPrice)
{
// 计算/确定书名,网址和价格的代码,这里......

return new 元组< string , string ,double>(bookTitle,bookURL,bookPrice);
}

当然,你可以使用一个Class,或者一个Struct;如果你想检查为什么你可能会使用元组,请参阅Eric Lippert的评论:[ ^ ]。



免责声明:我不熟悉WebForms及其局限性(如果有的话)。


Hi, so I have the following code:

public webSite4(double bookPrice, string titleBook, string getUrl) //bookamillion
        {
            // used on each read operation
            byte[] buf = new byte[8192];

            // prepare the web page we will be asking for
            string urlResult = string.Empty;

            if (string.IsNullOrEmpty(isbnEntry.Text))
            {
                bookEntry.Text.Replace(" ", "+");
                string urlTitle =
                    String.Format(
                    "http://www.booksamillion.com/search?id=5910205702379&query={0}&where=book_title&search.x=24&search.y=9&search=Search&affiliate=&sort=price_ascending",
                    bookEntry.Text);
                urlResult = urlTitle;

            }
            else if (string.IsNullOrEmpty(bookEntry.Text))
            {
                string urlIsbn =
                    String.Format(
                    "http://www.booksamillion.com/search?id=5910205702379&query={0}&where=isbn&search.x=16&search.y=8&search=Search&affiliate=&sort=price_ascending",
                isbnEntry.Text);
                urlResult = urlIsbn;
            }
            else
            {
                string urlBoth =
                    String.Format("http://www.booksamillion.com/search?id=5910205702379&query={0}&where=isbn&search.x=16&search.y=8&search=Search&affiliate=&sort=price_ascending",
                    isbnEntry.Text);
                urlResult = urlBoth;
            }

            // prepare request
            CookieContainer cookies = new CookieContainer();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlResult);
            HttpWebResponse response = null;

            // set header values
            request.Method = "GET";
            request.CookieContainer = cookies;

            // get response data
            response = (HttpWebResponse)request.GetResponse();


            string responseData = new StreamReader(response.GetResponseStream()).ReadToEnd();
            response.Close();

            string getPrice = string.Empty;
  
            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.OptionFixNestedTags = true;
            htmlDoc.LoadHtml(responseData); // load html            
            HtmlAgilityPack.HtmlNode rootNode = htmlDoc.DocumentNode;

            titleBook = rootNode.SelectSingleNode("/html/body/div[4]/div/div/div[2]/ol/li/div/span/a/img").Attributes["alt"].Value;

            getUrl = rootNode.SelectSingleNode(@"/html/body/div[4]/div/div/div[2]/ol/li/div/span/a").InnerHtml.ToString();

    
            getPrice = getPrice.Substring(15);
                    

            bookPrice = System.Convert.ToDouble(getPrice);

            double priceConvert = bookPrice * 0.73; //converts USdollars to euro

            string webSource = "BooksAMillion";
        }

The method basically gets data off a website (the book title, price and url).

The Idea is that I have 3 more methods with the same variables and need to compare all bookPrice results. This is done by having a return type to all of the needed methods and be able to get the bookPrice variable in one place and compare them.

Any help is much appreciated :)

Thanks!

解决方案

I would recommend having that method return an object[]. You can handle each item returned from the method call as needed.

The method signature would look something like this:

protected object[] ReturnMultipleTypes(object sender, EventArgs e)
        {
            object[] d = new object()[3];
            return d;
        }


Keep in mind the access modifier needs to be appropriate for your situation and the size of your array will be dependent on the number of items you need to return.


If you want to return multiple values of different Types from a method, but still want to use strong-typing, then using a Tuple is one way to do that. Example:

private void button1_Click(object sender, EventArgs e)
{
    var tt1 = method1("one", "two", 100.32D);

    string title = tt1.Item1;
    string bookURL = tt1.Item2;
    double price = tt1.Item3;
}

private Tuple<string, string, double> method1(string bookTitle, string bookURL, double bookPrice)
{
    // code to calculate/determine Book Title, URL, and Price, here ...

    return new Tuple<string, string, double>(bookTitle, bookURL, bookPrice);
}

Of course, you could use a Class, or, a Struct; if you want to examine why you might use a Tuple, see Eric Lippert's comments here: [^].

Disclaimer: I am not familiar with WebForms, and its limitations (if any).


这篇关于返回不同类型变量的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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