在 C# 中将 var 作为方法参数传递
Passing a var as a method parameter in C#
我正在尝试将 var
参数传递给方法:
class Program
{
static void Main()
{
var client = new RestClient("http://example.com");
var request = new RestRequest("resource/{id}", Method.POST);
var response = client.Execute(request);
PrintResponseStuff(response);
}
public static void PrintResponseStuff(var response)
{
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.StatusDescription);
Console.WriteLine(response.IsSuccessful);
Console.WriteLine(response.Content);
Console.WriteLine(response.ContentType);
}
}
最简单的方法是传递一个变量;但是,如果有一种数据类型可以容纳 request
,那么它也应该可以工作。无论如何都可以这样做,还是我需要单独传递每个项目?
var
不是 "type" 而只是编译器糖。它足够聪明,知道它是什么类型。事实上,您只需将鼠标悬停在上面即可看到它。
将 PrintResponseStuff
参数更改为该类型。
可以用object
或dynamic
,var
不行
看起来您正在使用 RestSharp,根据您的示例代码,您正在调用 RestClient.Execute()
,它可以 仅 return 和 IRestResponse
.所以你的代码很容易是:
static void Main()
{
var client = new RestClient("http://example.com");
var request = new RestRequest("resource/{id}", Method.POST);
//response is always IRestResponse if you call Execute()
var response = client.Execute(request);
PrintResponseStuff(response);
}
public static void PrintResponseStuff(IRestResponse response)
{
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.StatusDescription);
Console.WriteLine(response.IsSuccessful);
Console.WriteLine(response.Content);
Console.WriteLine(response.ContentType);
}
我正在尝试将 var
参数传递给方法:
class Program
{
static void Main()
{
var client = new RestClient("http://example.com");
var request = new RestRequest("resource/{id}", Method.POST);
var response = client.Execute(request);
PrintResponseStuff(response);
}
public static void PrintResponseStuff(var response)
{
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.StatusDescription);
Console.WriteLine(response.IsSuccessful);
Console.WriteLine(response.Content);
Console.WriteLine(response.ContentType);
}
}
最简单的方法是传递一个变量;但是,如果有一种数据类型可以容纳 request
,那么它也应该可以工作。无论如何都可以这样做,还是我需要单独传递每个项目?
var
不是 "type" 而只是编译器糖。它足够聪明,知道它是什么类型。事实上,您只需将鼠标悬停在上面即可看到它。
将 PrintResponseStuff
参数更改为该类型。
可以用object
或dynamic
,var
不行
看起来您正在使用 RestSharp,根据您的示例代码,您正在调用 RestClient.Execute()
,它可以 仅 return 和 IRestResponse
.所以你的代码很容易是:
static void Main()
{
var client = new RestClient("http://example.com");
var request = new RestRequest("resource/{id}", Method.POST);
//response is always IRestResponse if you call Execute()
var response = client.Execute(request);
PrintResponseStuff(response);
}
public static void PrintResponseStuff(IRestResponse response)
{
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.StatusDescription);
Console.WriteLine(response.IsSuccessful);
Console.WriteLine(response.Content);
Console.WriteLine(response.ContentType);
}