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

Can I check if a variable can be cast to a specified type?(我可以检查一个变量是否可以转换为指定的类型吗?)
本文介绍了我可以检查一个变量是否可以转换为指定的类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证是否可以将传递的变量转换为特定类型.我尝试了以下方法,但无法编译,所以我认为我的做法是错误的(我是 C# 新手)

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

我基本上是在尝试避免类似的大量 switch 语句

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":
      ...
  }

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

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

其中可能有诸如

"StartTime","System.DateTime",null
"TicketId","System.String","$[Ff][0-9]{7}^"

我的函数的输入将是一个 KeyValuePair,类似于

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");

我需要检查 KeyValuePair 的值是否属于 MetaDataType 预期的正确数据类型.

I need to check that the value of the KeyValuePair is of the correct datatype expected by the MetaDataType.

编辑答案:

Leon 非常接近我最终想出的解决方案.

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;

}

推荐答案

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

Use the "as" operator to attempt a cast:

var myObject = something as String;

if (myObject != null)
{
  // successfully cast
}
else
{
  // cast failed
}

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

If the cast fails, no exception is thrown, but the destination object will be Null.

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

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

这篇关于我可以检查一个变量是否可以转换为指定的类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)