|
-
December 17th, 2007, 02:47 PM
#1
Generics and type names.
I want to generate a correct type string by using reflection. The problem is that the generic types doesnt look like the declarations. Anyone know how to get the type name as it's declared?
For instance, List<string> becomes List`1, and it's FullName is System.Collections.Generic.List`1[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
I would like to get it back as List<string>.
Anyone got some code for this?
"The making of software, like the making of sausages, should never be watched."
http://blog.gauffin.org - .NET Coding/Architecture
-
December 17th, 2007, 02:57 PM
#2
Re: Generics and type names.
I'm not sure what you're trying to accomplish. What do you mean by correct type? A string is a string
If you want to figure out what type something is, wouldn't typeof be better?
-
December 17th, 2007, 03:16 PM
#3
Re: Generics and type names.
The following "does the work" (it is a snippet pulled from working code, it will NOT compile on its own
Code:
if (type.IsGenericType && !type.IsGenericTypeDefinition)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat(typeName.Substring(0, typeName.IndexOf('`')));
sb.Append("<");
bool first = true;
foreach (Type genericArgumentType in type.GetGenericArguments())
{
if (!first)
sb.Append(", ");
first = false;
sb.Append(GetTypeName(genericArgumentType));
}
sb.Append(">");
typeName = sb.ToString();
}
TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
2008, 2009,2010
In theory, there is no difference between theory and practice; in practice there is.
* Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions 
* How NOT to post a question here
* Of course you read this carefully before you posted
* Need homework help? Read this first
-
December 18th, 2007, 02:20 AM
#4
Re: Generics and type names.
ahh.. I didn't see GetGenericArguments method.
Thank you.
"The making of software, like the making of sausages, should never be watched."
http://blog.gauffin.org - .NET Coding/Architecture
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|