是否可以从另一个类的方法中获取多个值?

时间:2019-03-12 09:20:26

标签: c#

我有一个带有一些用于Web请求的方法的类,例如:

public class BiPRORequests
{
    private readonly string HOST;

    public BiPRORequests()
    {
        HOST = "server";
    }
    public RemoteCertificateValidationCallback ServerCertificateValidationCallback { get; set; }

    public string authenticate(string un, string pw)
    {
        try
        {
            HttpWebRequest request = HttpWebRequest.CreateHttp(string.Format("https://{0}/bipro/authenticate", HOST));
            request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

            request.Method = "POST";
            request.ContentType = "text/xml";

            string postData = @"some connection string" + un + pw;

            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.ContentLength = byteArray.Length;
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string bipro;
            if (response.StatusCode == HttpStatusCode.OK)
            {
                dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                string responseFromServer = reader.ReadToEnd();
                string te = Convert.ToString(response.StatusCode);;
                bipro = responseFromServer.Substring(821, 36);

                reader.Close();
                dataStream.Close();
                response.Close();
                return bipro;
            }
            return "error: ";
        }

        catch (WebException ex)
        {
            using (var stream = ex.Response.GetResponseStream())
            using (var reader = new StreamReader(stream))
            {
                string te = reader.ReadToEnd();
            }
            string exe = Convert.ToString(ex.Message);
            return exe;
        } }

我现在在另一个文件中有一个程序,如下所示:

 static void Main(string[] args)
    {
        BiPRORequests testcon = new BiPRORequests();
        string test = testcon.authenticate("username", "password"));  
    }

我的问题是,在authenticate方法中声明了几个变量,我想获取这些变量的“生成”值。我需要postData,responseFromServer和bipro,但是该方法只能返回一个值(bipro)。还有其他方法可以访问我的main方法中的值吗?

(我正在尝试获取它们,以便可以将它们与正确的值进行比较,以查看方法中是否存在任何错误。 我知道这个网站上也有几个类似的问题,但是我还没有找到可以帮助我的问题。)

1 个答案:

答案 0 :(得分:3)

有很多方法,具体取决于您需要的数量,对于某些值,最简洁的方法可能是命名元组

public (int SomeVal, string Another) authenticate(string un, string pw)
{
    ...
    return (2,"yay");
}

...

var result = testcon.authenticate("username", "password")); 
Console.WriteLine(result.SomeVal);
Console.WriteLine(result.Another);

C# tuple types

否则,您可能要创建一个类

public class Something
{

    // properties

    // easy constructor 
}


...

public Something authenticate(string un, string pw)
{

    ...
    return new Something(blah,blah);
}