我有一个变量返回数据类型为Object
。有时,它返回datetime
,有时返回bool
等。
但我不想使用if ... else
语句列出所有可能性并转换为正确的数据类型。
有什么方法可以使用convert.tostring(xxx)
,convert.toboolean(xxx)
?
您可能想要研究 Convert 类中的 Convert.ChangeType 方法。
这里有一个小例子可能会有所帮助
namespace UnitTest
{
using System;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine(ConvertToType(DateTime.Now).GetType().Name);
Console.WriteLine(ConvertToType<Guid>(Guid.NewGuid()).GetType().Name);
Console.Read();
}
public static dynamic ConvertToType(object obj)
{
//If you're unsure of the type you want to return.
return Convert.ChangeType(obj, obj.GetType());
}
public static T ConvertToType<T>(object obj)
{
//If you definitely know the type you want to return.
return (T)Convert.ChangeType(obj, typeof(T));
}
}
}
您可以通过使用动态对象概念来实现此目的。
动态对象概念
但我认为你根本做不到,你可以使用反射来编写一个方法:
var test = variable.ConvertIt();
其中,具有反射的 ConvertIt 可以在运行时强制转换变量并返回动态。但是现在如何使用测试变量?
对不起,我的英语不好。
这可能看起来很奇怪,但你的问题(不想使用if-else
)首先是特殊的。这似乎不可能以任何其他方式进行。创建数据类型是因为您不能只使用变量来处理所有类型的数据。这不仅是程序员的问题,也是编译器的问题。
try
{
int a = convert.toint32(x);
// Process a;
}
catch(Exception e)
{
try
{
string b = convert.tostring(x);
//Process b;
}
catch(Exception ex)
{
// and so on...
}
}
此外,这使用 Convert.To__
,如您所愿。