Jypeli  5
The simple game programming library
TypeHelper.cs
Siirry tämän tiedoston dokumentaatioon.
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 
6 namespace Jypeli
7 {
8  public abstract class TypeHelper
9  {
10  public static bool InheritsFrom( Type actual, Type expected )
11  {
12  Type t = actual;
13 
14  do
15  {
16  if ( t == expected ) return true;
17  t = t.BaseType;
18  } while ( t != null && t != typeof( object ) );
19 
20  return false;
21  }
22 
23  public static string ToString( Type type )
24  {
25  /* When objects of class Type are stored, things get a little
26  * tricky:
27  *
28  * The parameter type may be the type object of an instance
29  * of class Type (typeof(Type).GetType()). Such a type object
30  * has type System.RuntimeType, which is internal to the system.
31  * As such, creating instances of it is not allowed.
32  *
33  * In order to be able to read back the type objects, their type
34  * should be System.Type instead of System.RuntimeType.
35  */
36  var runtimeType = type.GetType();
37  if ( type == runtimeType )
38  {
39  return typeof( Type ).AssemblyQualifiedName;
40  }
41 
42  StringBuilder sb = new StringBuilder( type.AssemblyQualifiedName );
43  if ( !type.ContainsGenericParameters ) return sb.ToString();
44 
45  sb.Append( '<' );
46  Type[] genargs = type.GetGenericArguments();
47 
48  for ( int i = 0; i < genargs.Length; i++ )
49  {
50  sb.Append( TypeHelper.ToString( genargs[i] ) );
51  sb.Append( ',' );
52  }
53 
54  sb[sb.Length - 1] = '>';
55  return sb.ToString();
56  }
57 
58  public static Type Parse( string typeStr )
59  {
60  int genOpen = typeStr.IndexOf( '<' );
61  int genClose = typeStr.IndexOf( '>' );
62 
63  if ( genOpen < 0 && genClose < 0 ) return Type.GetType( typeStr );
64  if ( genOpen >= 0 && genClose < 0 ) throw new ArgumentException( "Unterminated < in type string: " + typeStr );
65  if ( genOpen < 0 && genClose >= 0 ) throw new ArgumentException( "Unexpected > in type string: " + typeStr );
66 
67  Type parsedType = Type.GetType( typeStr.Substring( 0, genOpen ) );
68  string[] genargStrings = typeStr.Substring( genOpen + 1, genClose - genOpen - 1 ).Split( ',' );
69  Type[] genargs = new Type[genargStrings.Length];
70 
71  for ( int i = 0; i < genargStrings.Length; i++ )
72  {
73  genargs[i] = TypeHelper.Parse( genargStrings[i] );
74  }
75 
76  return parsedType;
77  }
78  }
79 }
static bool InheritsFrom(Type actual, Type expected)
Definition: TypeHelper.cs:10
static string ToString(Type type)
Definition: TypeHelper.cs:23
static Type Parse(string typeStr)
Definition: TypeHelper.cs:58