我已经浏览了许多类似于这个问题的问题,但没有一个真正触及我想要做的事情。我所试图做的是从外部源读取的变量还包括它们的数据类型为字符串数组列表:带多种返回类型的方法
例子:
ID/Key Type Value/Data;
varName1 bool true;
varName2 string str;
varName3 int 5;
我然后存储这些对象到词典中包含多个字符串的对象,ID也用作关键字。
我想要做的是现在创建一个方法,该方法使用switch语句将字符串转换为正确的数据类型,并返回它,而无需在方法调用中指定任何内容。该函数应该是这个样子:
public ??? Method(string key)
{
if(dictionary.ContainsKey(ID))
{
Var temp = dictionary[ID];
switch (temp.Type)
{
case "bool":
return Convert.ToBoolean(temp.Value);
case "int"
return Convert.ToInt(temp.Value);
case "string"
return temp.Value;
}
}
return "NULL";
}
方法调用应该是这个样子:
int x = Method(string key);
string word = Method(string key);
boolean isTrue = Method(string key);
也许我错过了一些东西,但我还没有找到的东西,确实相当的东西喜欢这个。对此的任何和所有想法也是受欢迎的。
对不起,没有这样的事情在C#中。一种方法有一个固定的返回类型。你可以使用'object'作为你的返回类型,但你必须施放。 – adv12
你必须使该方法通用才能工作。当你使用它时,它最终会看起来像'string word =方法(key)'。你也必须做'bool?'和'int?'因为当你没有找到密钥时你想返回'null'。 –
juharr
如果你的值被存储为'Object',你可以做'(T)值'。什么阻止你从'string word =(string)方法(string key);',给定,方法返回'object' –