Nic*_*ick 43 c# casting type-conversion
我试图验证传递的变量是否可以转换为特定类型.我已经尝试了以下但是无法让它编译,所以我假设我正在以错误的方式(我是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;
}
Run Code Online (Sandbox Code Playgroud)
我基本上试图避免一个大规模的开关声明
switch(myType){
case "System.Int32":
try
{
var convertedValue = Convert.ToInt32(myValue);
}
catch (Exception)
{
canBeConverted = false;
}
break;
case "another type":
...
}
Run Code Online (Sandbox Code Playgroud)
编辑:
好的,基本上我有一个已知输入类型的db表,如下所示:
CREATE TABLE [dbo].[MetadataTypes] (
[typeName] VARCHAR (50) NOT NULL,
[dataType] VARCHAR (50) NOT NULL,
[typeRegex] VARCHAR (255) NULL
);
Run Code Online (Sandbox Code Playgroud)
可能有数据如
"StartTime","System.DateTime",null
"TicketId","System.String","$[Ff][0-9]{7}^"
Run Code Online (Sandbox Code Playgroud)
我的函数的输入将是一个KeyValuePair
myInput = new KeyValuePair<string,string>("StartTime","31/12/2010 12:00");
Run Code Online (Sandbox Code Playgroud)
我需要检查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;
}
Run Code Online (Sandbox Code Playgroud)
Leo*_*eon 54
使用"as"运算符尝试强制转换:
var myObject = something as String;
if (myObject != null)
{
// successfully cast
}
else
{
// cast failed
}
Run Code Online (Sandbox Code Playgroud)
如果转换失败,则不会抛出异常,但目标对象将为Null.
编辑:
如果你知道你想要什么类型的结果,你可以使用这样的辅助方法:
public static Object TryConvertTo<T>(string input)
{
Object result = null;
try
{
result = Convert.ChangeType(input, typeof(T));
}
catch
{
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
ker*_*ode 10
试试这个
return myType.IsInstanceOfType(myObject);
Run Code Online (Sandbox Code Playgroud)
我想这就是你要找的东西:
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
}
Run Code Online (Sandbox Code Playgroud)
编辑:只是要清楚,运营商is和as以下方式使用...
所述is操作者将返回一个boolean值以指示所述对象是否被测试或者是指定的类型或实现指定的接口.这就像问编译器"我的变量是这种类型吗?":
var someString = "test";
var result = someString is IComparable; // result will be true
Run Code Online (Sandbox Code Playgroud)
在as操作者试图执行转换,并返回一个null如果不能参考.这就像告诉编译器"我想将此变量用作此类型":
var someString = "test";
var comparable = someString as IComparable; // comparable will be of type String
Run Code Online (Sandbox Code Playgroud)
如果您尝试这样做:
var someString = "42";
// using Int32? because the type must be a reference type to be used with as operator
var someIntValue = someString as Int32?;
Run Code Online (Sandbox Code Playgroud)
编译器将发出错误:
无法通过内置转换转换类型.
签出此链接:http : //msdn.microsoft.com/zh-cn/library/scekt9xw(v=vs.71).aspx
is运算符用于检查对象的运行时类型是否与给定类型兼容。is运算符用于以下形式的表达式:
if (expression is type){
// do magic trick
}
Run Code Online (Sandbox Code Playgroud)
您可以使用一些东西吗?
| 归档时间: |
|
| 查看次数: |
61401 次 |
| 最近记录: |