首页 文章

我可以检查一个变量是否可以转换为指定的类型吗?

提问于
浏览
37

我试图验证传递的变量是否可以转换为特定类型 . 我已经尝试了以下但是无法让它编译,所以我假设我正在以错误的方式(我是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 回答

  • 9

    试试这个

    return myType.IsInstanceOfType(myObject);
    
  • 47

    使用“as”运算符尝试强制转换:

    var myObject = something as String;
    
    if (myObject != null)
    {
      // successfully cast
    }
    else
    {
      // cast failed
    }
    

    如果转换失败,则不会抛出异常,但目标对象将为Null .

    EDIT:

    如果你知道你想要什么类型的结果,你可以使用这样的辅助方法:

    public static Object TryConvertTo<T>(string input)
    {
        Object result = null;
        try
        {
            result = Convert.ChangeType(input, typeof(T));
        }
        catch
        {
        }
    
        return result;
    }
    
  • 4

    我想这就是你要找的东西:

    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
    }
    

    EDIT :为了清楚起见,运营商 isas 以下列方式使用......

    is 运算符将返回 boolean 值,以指示正在测试的对象是指定的类型还是实现指定的接口 . 这就像问编译器"Is my variable this type?":

    var someString = "test";
    var result = someString is IComparable; // result will be true
    

    as 运算符尝试执行转换,如果不能,则返回 null 引用 . 这就像告诉编译器"I would like to use this variable as this type":

    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?;
    

    编译器将发出错误:

    无法通过内置转换转换类型 .

  • 1

    点击此链接:http://msdn.microsoft.com/en-us/library/scekt9xw(v=vs.71).aspx

    is运算符用于检查对象的运行时类型是否与给定类型兼容 . is运算符用于表单的表达式:

    if (expression is type){
        // do magic trick
    }
    

    你可以用的东西?

  • 5

    您是否尝试过具有布尔返回值的TryParse来指示转换是否成功

  • 1

    你可以做 int.TryParse() 功能:

    int myInt;
    bool parsed = int.TryParse(myVariable, out myInt);
    
    if (parsed) {
        // Do something with myInt or other logic
    }
    

相关问题