在我的函数中,我正在获取一个字符串。
但是,我想使用相同的函数返回int,bool或字符串。说我通过其他一些函数得到了一个字符串:
public object read(string whatstring, string returnhow="string") {
object result = "a string gotten from another function";
switch(returnhow){
case "int":
result = int.TryParse(result, out result); break;
case "bool":
if (result=="0" || result=="false" || result=="") { returnthis = false; } else { returnthis = true; }; break;
default:
result = result.ToString(); break;
}
return result;
}
我想这样称呼它:
string thisvar = read("300", "int");
//or
bool thisvar = read("true", "string");
我认为这是不对的。我可以解决它,还是我走错了方向?
我想是因为我调用该函数的方式而出现错误,但是您对我想要的东西有所了解。我希望它作为声明返回值的
type
返回。也许我走错了方向?Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)
最佳答案
这是一个示例实现:
public static T GetByType<T> (string input) {
if(typeof(T) == typeof(string)) { return (T) Convert.ChangeType(input, typeof(T)); }
if(typeof(T) == typeof(Int32)) {
int output;
if(int.TryParse(input, out output)) { return (T) Convert.ChangeType(output, typeof(T)); }
}
if(typeof(T) == typeof(bool)) {
return (T) Convert.ChangeType(input == "1", typeof(T));
}
throw new ArgumentException("Invalid input");
}
工作示例:
void Main()
{
Console.WriteLine ("Calling with string:");
object type = GetByType<string>("0");
Console.WriteLine (type.GetType());
Console.WriteLine ("Calling with boolean:");
type = GetByType<bool>("0");
Console.WriteLine (type.GetType());
Console.WriteLine ("Calling with integer:");
type = GetByType<int>("0");
Console.WriteLine (type.GetType());
Console.WriteLine ("Calling with DateTime:");
type = GetByType<DateTime>("0");
Console.WriteLine (type.GetType());
}
输出: