有没有办法去注射"方法中的点之后的变量,例如Console.variableLine();

时间:2017-06-17 15:12:20

标签: c#

var summoner = api.GetSummoner(Region.euw, "AlexK");    

我想把euw变成一个变量。喜欢这个

Console.WriteLine("Type your server") //and I type for example one of the following (eune,euw,na)
string server = Console.ReadLine();
var summoner = api.GetSummoner(Region.server, "AlexK");

另一个例子是

Console.WriteLine("Type if you want to Read or Write");
string preference = Console.ReadLine();
Console.preferenceLine() //There is no practical use for this one just giving an example of where I want to place the variable.

我使用的C#包装器就是这个https://github.com/BenFradet/RiotSharp 我对C#很新,所以ELI5或发送一些链接 提前谢谢。

1 个答案:

答案 0 :(得分:0)

取决于点运算符之后的,这必须以不同方式处理。

如果您想根据输入调用方法,可以use reflection。但是,除非您处理未知类型(当方法名称仅在运行时知道时),否则最好使用if语句分支代码。

if (method == "read")
{
    string input = Console.ReadLine();
    var summoner = api.GetSummoner(server, "AlexK");
    // TODO: do something with the summoner
}
if (method == "write")
{
    Console.WriteLine("Printing data:")
    // TODO: print data
}

这与枚举形成鲜明对比,枚举是一种完全不同的语言结构,可以从文本中轻松解析。

string input = Console.ReadLine();
Region region = Enum.Parse(typeof(Region), input);
var summoner = api.GetSummoner(region, "AlexK");