Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

reflection - What's the difference between System.Type and System.RuntimeType in C#?

I was trying to do some convention tests today, and getting all the types in an assembly (by calling Assembly.GetTypes()), when I stumbled into something:

System.RuntimeType:[First.Namespace.FirstClass]

Whenever I try to compare that type with typeof(FirstClass), they're not equal. So, when I try to find all the types that contain FirstClass as a generic parameter, I'm not finding any.

What's the difference between System.RuntimeType and System.Type?

Is there any way to solve my problem?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

System.RuntimeType is a concrete class that derives from the abstract base class System.Type. Since System.RuntimeType is not public, you will typically encounter instances of it as System.Type.

Confusion can arise when you are trying to get the type of an object and mistakenly call GetType() on another object representing the first object's type, rather than just using that object directly. Then Type.ToString() will return "System.RuntimeType" when the object it is called on is representing a Type:

string str = string.Empty;
Type strType = str.GetType();
Type strTypeType = strType.GetType();
strType.ToString();     // returns "System.string"
strTypeType.ToString(); // returns "System.RuntimeType"

For example, in this blog post someone is trying to get the type of a column in a database, doing something like this:

object val = reader.GetFieldType(index);
Type runtimeType = val.GetType();
PropertyInfo propInfo = runtimeType.GetProperty("UnderlyingSystemType");
Type type = (Type)propInfo.GetValue(val, null);

Since val is already a Type object, val.GetType() will return another Type object representing the type System.RuntimeTime as this is the concrete type used to represent the original type object. The blog post then shows some unnecessary reflection trickery, to get the type of the original type object, when really all that was required was:

Type type = reader.GetFieldType(index) as Type;

So if your Type object is reporting that it represents a System.RuntimeType, make sure you have not accidentally called GetType() on a type you have already got.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...