How can I get the correct text definition of a generic type using reflection?

前端 未结 6 1339
萌比男神i
萌比男神i 2020-12-01 14:17

I am working on code generation and ran into a snag with generics. Here is a \"simplified\" version of what is causing me issues.

Dictionary

        
6条回答
  •  暖寄归人
    2020-12-01 14:49

    This evening I was toying a bit with extension methods and I tried to find an answer for your question. Here is the result: it's a no-warranty code. ;-)

    internal static class TypeHelper
    {
        private const char genericSpecialChar = '`';
        private const string genericSeparator = ", ";
    
        public static string GetCleanName(this Type t)
        {
            string name = t.Name;
            if (t.IsGenericType)
            {
                name = name.Remove(name.IndexOf(genericSpecialChar));
            }
            return name;
        }
    
        public static string GetCodeDefinition(this Type t)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("{0}.{1}", t.Namespace, t.GetCleanName());
            if (t.IsGenericType)
            {
                var names = from ga in t.GetGenericArguments()
                            select GetCodeDefinition(ga);
                sb.Append("<");
                sb.Append(string.Join(genericSeparator, names.ToArray()));
                sb.Append(">");
            }
            return sb.ToString();
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            object[] testCases = { 
                                    new Dictionary(),
                                    new List(),
                                    new List>(),
                                    0
                                };
            Type t = testCases[0].GetType();
            string text = t.GetCodeDefinition();
            Console.WriteLine(text);
        }
    }
    

提交回复
热议问题