Home > Backend Development > C#.Net Tutorial > How to implement forced conversion and attempted conversion in C#

How to implement forced conversion and attempted conversion in C#

黄舟
Release: 2017-10-05 15:31:55
Original
2457 people have browsed it

This article mainly introduces the methods of C# forced conversion and attempted conversion in detail. It has certain reference value. Interested friends can refer to it.

The example in this article shares with everyone the C# forced conversion method. The method of conversion and attempt to convert is for your reference. The specific content is as follows

Convert the Object type of String[] type to the String[] type:


public string ObjectToString(object ob)
{
  string str = string.Empty;
  if (ob is string[])
  {
    string[] strList = (string[])ob; 
  }

  return str;
}
Copy after login

Use is to determine whether ob is of string[] type.

Convert string type to DateTime type:


public DateTime StringToDateTime(string str)
{
  DateTime dateTime = new DateTime();
  if (DateTime.TryParse(str, out dateTime))
  {
    return dateTime;
  }
  return dateTime;
}
Copy after login

Note:

Use DateTime.TryParse() ; When performing conversion judgment, if true is returned, the forced conversion result will be passed into DateTime; if false is returned, forced conversion cannot be performed.

You can also use Convert.ToDateTime(); to perform forced conversion, but it is impossible to determine whether forced conversion is possible. When forced conversion is not possible, an exception will be reported.

The above is the detailed content of How to implement forced conversion and attempted conversion in C#. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template