从ObservableCollection <string>?</string> </system.string>的Type中获取字符串“System.Collections.ObjectModel.ObservableCollection <system.string>”

时间:2011-12-23 12:12:16

标签: c# types observablecollection

我正在解析一些DLL,我必须生成一些将被编译的代码。 目前,一切正常,但现在,我们必须处理集合&lt;&gt;类型,这是问题。 在ObservableCollection的情况下,我们得到了FullName为的类型:

"System.Collections.ObjectModel.ObservableCollection`1[System.String]"

并且考虑到我正在处理对象(我可以从DLL中读取任何内容),生成的代码应该是:

var obj7 = (System.Collections.ObjectModel.ObservableCollection<System.String>) myParsedProperty; //This code will, then, be compiled + executed

所以......有没有一种简单的方法可以从Type中做到这一点,还是我必须在Strings上做一些重要的事情? (操纵propType.Name .Namespace和.GetGenericArguments()...)

1 个答案:

答案 0 :(得分:1)

这是最简单的方法:

//...
    Type type = typeof(IList<string>);
    string definition = GetGenericTypeDefinitionString(type);
    //definition is "System.Collections.Generic.IList<System.String>"
}

static string GetGenericTypeDefinitionString(Type genericType) {
    string genericTypeDefName = genericType.GetGenericTypeDefinition().FullName;
    string typePart = genericTypeDefName.Substring(0, genericTypeDefName.IndexOf('`'));
    string argumentsPart = string.Join(",",
        Array.ConvertAll(genericType.GetGenericArguments(), (t) => t.FullName));
    return string.Concat(typePart, '<', argumentsPart, '>');
}

您也可以尝试使用Code.Dom:

using System.CodeDom;
using Microsoft.CSharp;
//...
Type targetType = typeof(IList<string>);
//...
CSharpCodeProvider provider = new CSharpCodeProvider();
CodeExpression cast = new CodeCastExpression(targetType, new CodeVariableReferenceExpression("genericCollection"));
CodeStatement statement = new CodeVariableDeclarationStatement(new CodeTypeReference(targetType), "list", cast);
using(StringWriter writer = new StringWriter()) {
    provider.GenerateCodeFromStatement(statement, writer, null);
    string expression = writer.ToString();
   // expression is "System.Collections.Generic.IList<string> list = ((System.Collections.Generic.IList<string>)(genericCollection));"
}