Jypeli 10
The simple game programming library
TypeHelper.cs
Siirry tämän tiedoston dokumentaatioon.
1using System;
2using System.Text;
3
4namespace Jypeli
5{
9 public abstract class TypeHelper
10 {
17 public static bool InheritsFrom( Type actual, Type expected )
18 {
19 Type t = actual;
20
21 do
22 {
23 if ( t == expected ) return true;
24 t = t.BaseType;
25 } while ( t != null && t != typeof( object ) );
26
27 return false;
28 }
29
35 public static string ToString( Type type )
36 {
37 /* When objects of class Type are stored, things get a little
38 * tricky:
39 *
40 * The parameter type may be the type object of an instance
41 * of class Type (typeof(Type).GetType()). Such a type object
42 * has type System.RuntimeType, which is internal to the system.
43 * As such, creating instances of it is not allowed.
44 *
45 * In order to be able to read back the type objects, their type
46 * should be System.Type instead of System.RuntimeType.
47 */
48 var runtimeType = type.GetType();
49 if ( type == runtimeType )
50 {
51 return typeof( Type ).AssemblyQualifiedName;
52 }
53
54 StringBuilder sb = new StringBuilder( type.AssemblyQualifiedName );
55
56#if WINDOWS_STOREAPP
57 if ( !type.IsConstructedGenericType ) return sb.ToString();
58 Type[] genargs = type.GenericTypeArguments;
59#else
60 if ( !type.ContainsGenericParameters ) return sb.ToString();
61 Type[] genargs = type.GetGenericArguments();
62#endif
63
64 sb.Append( '<' );
65
66 for ( int i = 0; i < genargs.Length; i++ )
67 {
68 sb.Append( TypeHelper.ToString( genargs[i] ) );
69 sb.Append( ',' );
70 }
71
72 sb[sb.Length - 1] = '>';
73 return sb.ToString();
74 }
75
81 public static Type Parse( string typeStr )
82 {
83 int genOpen = typeStr.IndexOf( '<' );
84 int genClose = typeStr.IndexOf( '>' );
85
86 if ( genOpen < 0 && genClose < 0 ) return Type.GetType( typeStr );
87 if ( genOpen >= 0 && genClose < 0 ) throw new ArgumentException( "Unterminated < in type string: " + typeStr );
88 if ( genOpen < 0 && genClose >= 0 ) throw new ArgumentException( "Unexpected > in type string: " + typeStr );
89
90 Type parsedType = Type.GetType( typeStr.Substring( 0, genOpen ) );
91 string[] genargStrings = typeStr.Substring( genOpen + 1, genClose - genOpen - 1 ).Split( ',' );
92 Type[] genargs = new Type[genargStrings.Length];
93
94 for ( int i = 0; i < genargStrings.Length; i++ )
95 {
96 genargs[i] = TypeHelper.Parse( genargStrings[i] );
97 }
98
99 return parsedType;
100 }
101 }
102}
Avustava luokka tietotyyppien käsittelyyn
Definition: TypeHelper.cs:10
static bool InheritsFrom(Type actual, Type expected)
Periytyykö luokka toisesta
Definition: TypeHelper.cs:17
static string ToString(Type type)
Tyypin nimi merkkijonona
Definition: TypeHelper.cs:35
static Type Parse(string typeStr)
Parsii tyypin annetysta merkkijonosta
Definition: TypeHelper.cs:81