我可以检查一个变量可以转换到指定的类型? [英] Can I check if a variable can be cast to a specified type?
问题描述
我试图验证传递变量是否可以被转换为特定的类型。我曾尝试以下,但不能得到它来编译,所以我认为我会约了错误的方式(我是新的C#)
字符串=的myTypeSystem.Int32;
串myvalue的=42;
布尔canBeCast = FALSE;
尝试
{
//尝试将值转换到它的预期类型以看它是否有效。
VAR的结果=(Type.GetType(typeString))dataValue;
canBeCast = TRUE;
}
抓
{
canBeCast = FALSE;
}
基本上,我试图避免沿线的一个巨大的switch语句
开关(的myType){
案System.Int32:
试
$ { b $ b VAR convertedValue = Convert.ToInt32(myvalue的);
}
赶上(例外)
{
canBeConverted = FALSE;
}
中断;
案另一类型:
:
}
编辑:
好了,基本上我认识的输入类型的数据库表,看起来像:
CREATE TABLE [DBO]。[MetadataTypes(
[typeName的] VARCHAR(50)NOT NULL,
[的dataType] VARCHAR(50)NOT NULL,
[typeRegex] VARCHAR(255)NULL
);
可能有诸如
<$ P数据$ p>
开始时间,System.DateTime的空
TicketId,System.String,$ [FF] [0-9] {7} ^
和输入到我的功能将是一个KeyValuePair沿
线
myInput =新KeyValuePair<字符串,字符串>(开始时间,31/12/2010 12:00);
我要检查KeyValuePair的值是由MetaDataType期望的正确数据类型。
编辑答案:
莱昂得到真正贴近我终于想出了解决方案。
有关引用我的函数现在看起来是这样的:
公共布尔ValidateMetadata(KeyValuePair<字符串,字符串>的DataItem)
{
//查找带有名称匹配
MetadataType类型= _repository.GetMetadataTypes()已知的元数据的SingleOrDefault(T =方式> t.typeName == dataItem.Key);
如果(类型== NULL){返回false; }
//获取的数据类型,并尝试以匹配数据项的通过。
布尔isCorrectType = FALSE;
串typeString = type.dataType;
串dataValue = dataItem.Value;
试
{
VAR cValue = Convert.ChangeType(dataValue,Type.GetType(typeString));
isCorrectType = TRUE;
}
抓
{
isCorrectType = FALSE;
}
// TODO:验证对这里可能正则表达式....
返回isCorrectType;
}
使用的作为经营者尝试转换:
VAR myObject的=东西为String
如果(myObject的!= NULL)
{
#成功投
}
,否则
{
#cast失败
}
如果转换失败,不会抛出异常,但目标对象为null。
编辑:
如果你知道你想要什么类型的结果,你可以使用一个辅助方法是这样的:
公共静态对象TryConvertTo< T>(字符串输入)
{
对象result = NULL;
试
{
结果= Convert.ChangeType(输入的typeof(T));
}
抓
{
}
返回结果;
}
I am trying to verify whether a variable that is passed can be converted to a specific type. I have tried the following but can't get it to compile so I assume I'm going about it the wrong way (I'm new to 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;
}
I'm basically trying to avoid a massive switch statement along the lines of
switch(myType){
case "System.Int32":
try
{
var convertedValue = Convert.ToInt32(myValue);
}
catch (Exception)
{
canBeConverted = false;
}
break;
case "another type":
...
}
EDIT:
Ok, basically I have a db table of known input types that looks like:
CREATE TABLE [dbo].[MetadataTypes] (
[typeName] VARCHAR (50) NOT NULL,
[dataType] VARCHAR (50) NOT NULL,
[typeRegex] VARCHAR (255) NULL
);
which may have data such as
"StartTime","System.DateTime",null
"TicketId","System.String","$[Ff][0-9]{7}^"
And the input to my function would be a KeyValuePair along the lines of
myInput = new KeyValuePair<string,string>("StartTime","31/12/2010 12:00");
I need to check that the value of the KeyValuePair is of the correct datatype expected by the MetaDataType.
EDIT FOR ANSWER:
Leon got really close to the solution I finally came up with.
For reference my function now looks like this:
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;
}
Use the "as" operator to attempt a cast:
var myObject = something as String
if (myObject != null)
{
# successfully cast
}
else
{
#cast failed
}
If the cast fails, no exception is thrown, but the destination object will be Null.
EDIT:
if you know what type of result you want, you can use a helper method like this:
public static Object TryConvertTo<T>(string input)
{
Object result = null;
try
{
result = Convert.ChangeType(input, typeof(T));
}
catch
{
}
return result;
}
这篇关于我可以检查一个变量可以转换到指定的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!