我正在尝试验证传递的变量是否可以转换为特定类型。我尝试过以下但是无法编译,所以我认为我的方法是错误的(我是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}^"
我的函数的输入将是
行的KeyValuePairmyInput = 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;
}
答案 0 :(得分:49)
使用“as”运算符尝试强制转换:
var myObject = something as String;
if (myObject != null)
{
// successfully cast
}
else
{
// cast failed
}
如果转换失败,则不会抛出任何异常,但目标对象将为Null。
修改强>
如果你知道你想要什么类型的结果,你可以使用这样的辅助方法:
public static Object TryConvertTo<T>(string input)
{
Object result = null;
try
{
result = Convert.ChangeType(input, typeof(T));
}
catch
{
}
return result;
}
答案 1 :(得分:10)
试试这个
return myType.IsInstanceOfType(myObject);
答案 2 :(得分:5)
我认为这就是你要找的东西:
var myValue = "42";
int parsedValue;
if (Int32.TryParse(myValue, out parsedValue)) {
// it worked, and parsedValue is equal to 42
}
else {
// it did not work and parsedValue is unmodified
}
编辑:为了清楚起见,操作符is
和as
以下列方式使用...
is
运算符将返回boolean
值,以指示正在测试的对象是指定的类型还是实现指定的接口。这就像问编译器“我的变量是这种类型吗?”:
var someString = "test";
var result = someString is IComparable; // result will be true
as
运算符尝试执行转换,如果不能,则返回null
引用。这就像告诉编译器“我想将此变量用作此类型”:
var someString = "test";
var comparable = someString as IComparable; // comparable will be of type String
如果您尝试这样做:
var someString = "42";
// using Int32? because the type must be a reference type to be used with as operator
var someIntValue = someString as Int32?;
编译器将发出错误:
无法通过内置转换转换类型。
答案 3 :(得分:4)
结帐此链接:http://msdn.microsoft.com/en-us/library/scekt9xw(v=vs.71).aspx
is运算符用于检查对象的运行时类型是否与给定类型兼容。 is运算符用于表达式:
if (expression is type){
// do magic trick
}
你可以使用的东西吗?
答案 4 :(得分:1)
您是否尝试过具有布尔返回值的TryParse来指示转换是否成功
答案 5 :(得分:1)
您可以执行int.TryParse()
功能:
int myInt;
bool parsed = int.TryParse(myVariable, out myInt);
if (parsed) {
// Do something with myInt or other logic
}
答案 6 :(得分:0)
我知道它已经很老了,但是对于以现代方式寻找答案的人,会留下回复。从C#7开始,您可以使用具有模式匹配(https://docs.microsoft.com/pl-pl/dotnet/csharp/pattern-matching)的新开关
switch (myObject)
{
case PlayerObject playerObject:
//this is player object type and can use also playerObject because it's already casted
break;
case EnemyObject enemyObject:
//same here but we have enemy object type
break;
default:
break;
}