我查看了许多与此类似的问题,但没有一个真正涉及到我想要做的事情。我想要做的是从外部源读取包含它们的数据类型在内的变量列表,并将它们存储在一个字符串数组中:
例子:
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);
bool isTrue = Method(string key);
也许我错过了什么,但我还没有找到像这样真正能做到这件事的东西。欢迎任何关于此的想法。
string word = Method<string>(key)
的样子。此外,你还需要使用bool?
和int?
,因为你想在未找到键时返回null
。 - juharr(T)value
。如果方法返回“object”,那么为什么不使用string word = (string)Method(string key);
呢? - T.S.public IKnowHowToconvertData Method<T>(string key)
。 - T.S.