Created
June 15, 2015 03:02
-
-
Save rutcreate/410cf6e19d4786382a3d to your computer and use it in GitHub Desktop.
Unity3D: String extension ToInt(), ToFloat(), ToBool(), BetterFormat().
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class StringExample { | |
| private int intFromString; | |
| private float floatFromString; | |
| private bool boolFromString; | |
| private string format = "Hi {Name} {Last}, I'm {Age} years old. I'm from {Country}."; | |
| private string formattedString; | |
| public StringExample { | |
| intFromString = "1".ToInt(); | |
| floatFromString = "2.123".ToFloat(); | |
| boolFromString = "True".ToBool(); | |
| formattedString = format.BetterFormat(new { Name = "John", Last = "Doe", Age = 21, Country = "Thailand" }); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.ComponentModel; | |
| namespace Opendream.Extension { | |
| public static class StringExtension { | |
| public static int ToInt(this string s) { | |
| int result = 0; | |
| int.TryParse(s, out result); | |
| return result; | |
| } | |
| public static float ToFloat(this string s) { | |
| float result = 0; | |
| float.TryParse(s, out result); | |
| return result; | |
| } | |
| public static bool ToBool(this string s) { | |
| return (string.Compare(s, "True", System.StringComparison.OrdinalIgnoreCase) == 0); | |
| } | |
| /// <summary> | |
| /// Betters the format. | |
| /// See http://stackoverflow.com/a/4077118/1597295. | |
| /// </summary> | |
| /// <returns>The format.</returns> | |
| /// <param name="format">Format.</param> | |
| /// <param name="source">Source.</param> | |
| public static string BetterFormat(this string format, object source) { | |
| if (format == null) { | |
| throw new ArgumentNullException("format"); | |
| } | |
| string result = format; | |
| foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(source)) { | |
| result = result.Replace("{" + prop.Name + "}", (prop.GetValue(source) ?? "(null)").ToString()); | |
| } | |
| return result; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment