我试图验证传递的变量是否可以转换为特定类型 . 我已经尝试了以下但是无法让它编译,所以我假设我正在以错误的方式(我是C#的新手)
string myType = "System.Int32";
string myValue = "42";
bool canBeCast = false;
try
{
// try to convert the value to it's intended type to see if it's valid.
var result = (Type.GetType(typeString))dataValue;
canBeCast = true;
}
catch
{
canBeCast = false;
}
我基本上试图避免一个大规模的开关声明
switch(myType){
case "System.Int32":
try
{
var convertedValue = Convert.ToInt32(myValue);
}
catch (Exception)
{
canBeConverted = false;
}
break;
case "another type":
...
}
编辑:
好的,基本上我有一个已知输入类型的db表,如下所示:
CREATE TABLE [dbo].[MetadataTypes] (
[typeName] VARCHAR (50) NOT NULL,
[dataType] VARCHAR (50) NOT NULL,
[typeRegex] VARCHAR (255) NULL
);
可能有数据如
"StartTime","System.DateTime",null
"TicketId","System.String","$[Ff][0-9]{7}^"
我的函数的输入将是一个KeyValuePair
myInput = new KeyValuePair<string,string>("StartTime","31/12/2010 12:00");
我需要检查KeyValuePair的值是否为MetaDataType所期望的正确数据类型 .
编辑答案:
Leon非常接近我最终提出的解决方案 .
作为参考我的功能现在看起来像这样:
public Boolean ValidateMetadata(KeyValuePair<string, string> dataItem)
{
// Look for known metadata with name match
MetadataType type = _repository.GetMetadataTypes().SingleOrDefault(t => t.typeName == dataItem.Key);
if (type == null) { return false; }
// Get the data type and try to match to the passed in data item.
Boolean isCorrectType = false;
string typeString = type.dataType;
string dataValue = dataItem.Value;
try
{
var cValue = Convert.ChangeType(dataValue, Type.GetType(typeString));
isCorrectType = true;
}
catch
{
isCorrectType = false;
}
//TODO: Validate against possible regex here....
return isCorrectType;
}
6 回答
试试这个
使用“as”运算符尝试强制转换:
如果转换失败,则不会抛出异常,但目标对象将为Null .
EDIT:
如果你知道你想要什么类型的结果,你可以使用这样的辅助方法:
我想这就是你要找的东西:
EDIT :为了清楚起见,运营商
is
和as
以下列方式使用......is
运算符将返回boolean
值,以指示正在测试的对象是指定的类型还是实现指定的接口 . 这就像问编译器"Is my variable this type?":as
运算符尝试执行转换,如果不能,则返回null
引用 . 这就像告诉编译器"I would like to use this variable as this type":如果您尝试这样做:
编译器将发出错误:
点击此链接:http://msdn.microsoft.com/en-us/library/scekt9xw(v=vs.71).aspx
你可以用的东西?
您是否尝试过具有布尔返回值的TryParse来指示转换是否成功
你可以做
int.TryParse()
功能: