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

我正在尝试验证传递的变量是否可以转换为特定类型。 我已经尝试了以下内容,但无法对其进行编译,因此我认为我将以错误的方式进行操作(我是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语句

  switch(myType){
    case "System.Int32":
      try
      {
        var convertedValue = Convert.ToInt32(myValue);
      }
      catch (Exception)
      {
        canBeConverted = false;
      }
      break;
    case "another type":
      ...
  }

编辑:

好的,基本上我有一个已知输入类型的数据库表,如下所示:

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;

}
Nick asked 2020-08-12T05:05:26Z
6个解决方案
54 votes

使用“ 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;
}
Leon answered 2020-08-12T05:05:46Z
10 votes

试试这个

return myType.IsInstanceOfType(myObject);
kernowcode answered 2020-08-12T05:06:06Z
6 votes

我认为这是您要寻找的:

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
}

编辑:只是要清楚,运算符isas以下列方式使用...

as操作员将返回null值,以指示被测试的对象是指定的类型还是实现的接口。 这就像问编译器“我的变量是这种类型吗?”:

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

编译器将发出错误:

无法通过内置转换来转换类型。

Yuck answered 2020-08-12T05:06:54Z
5 votes

签出此链接:[http://msdn.microsoft.com/zh-cn/library/scekt9xw(v=vs.71).aspx]

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

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

您可以使用一些东西吗?

321X answered 2020-08-12T05:07:25Z
1 votes

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

kd7 answered 2020-08-12T05:07:45Z
1 votes

您可以执行int.TryParse()功能:

int myInt;
bool parsed = int.TryParse(myVariable, out myInt);

if (parsed) {
    // Do something with myInt or other logic
}
evasilchenko answered 2020-08-12T05:08:06Z
translate from https://stackoverflow.com:/questions/7042314/can-i-check-if-a-variable-can-be-cast-to-a-specified-type