Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

c# - Can I check if a variable can be cast to a specified type?

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

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

EDIT:

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

which may have data such as

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

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

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

EDIT FOR ANSWER:

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;

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the "as" operator to attempt a cast:

var myObject = something as String;

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

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

EDIT:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...