locked
コードをはってみる RRS feed

  • General discussion

  • いい感じですね。

    1     class Program  
    2     {  
    3         static void Main(string[] args)  
    4         {  
    5             Console.WriteLine(ToType<Decimal>("10.2", 0m));  
    6             Console.WriteLine(ToType<Boolean>("true"false));  
    7             Console.WriteLine(ToType<Point>("10,2"new Point(0,0)));  
    8             Console.WriteLine(ToType<Member>("Cat", Member.Animal));  
    9             Console.WriteLine(ToType<Member>("Error", Member.Animal));  
    10         }  
    11  
    12         static public T ToType<T>(object value, T defaultValue)  
    13         {  
    14           if (value == nullreturn defaultValue;  
    15           var s = value.ToString();  
    16           if (string.IsNullOrEmpty(s)) return defaultValue;  
    17  
    18             var c = TypeDescriptor.GetConverter(typeof(T));  
    19           try {  
    20               return (T)c.ConvertFromString(s);  
    21           }  
    22           catch {  
    23             return defaultValue;  
    24           }  
    25         }  
    26     }  
    27     enum Member  
    28     {  
    29         Dog, Cat, Animal  
    30     }  
    31  

     


    えムナウ@わんくま同盟 Microsoft MVP Visual Studio C# Since 2005/01-2009/12
    Friday, January 23, 2009 12:21 PM

All replies

  •  コードきれいに貼れるんですね~(^^)
    楽しみです。

    1 public class Greeter  
    2 {  
    3     public void Greet()  
    4     {  
    5         Console.WriteLine("Hello world");  
    6     }  
    7

    かずき Blog:http://blogs.wankuma.com/kazuki/
    Sunday, January 25, 2009 3:48 PM