blu*_*ish 10 .net c# generics reflection fully-qualified-naming
我有一个MyObject带有property(MyProperty)的object ().我想要得到它的类型名称(即String或MyClass等).我用:
PropertyInfo propInfo = typeof(MyObject).GetProperty("MyProperty");
Console.WriteLine(propInfo.PropertyType.Name);
Console.WriteLine(propInfo.PropertyType.FullName);
Run Code Online (Sandbox Code Playgroud)
简单类型没有问题,但是当MyProperty它是泛型类型时,我在获取它的名字方面遇到了问题(例如Collection<String>).它打印:
Collection`1
System.Collections.ObjectModel.Collection`1 [[System.String,mscorlib,Version = 2.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]
那是什么`1?我怎样才能获得" Collection<String>"?
Geo*_*ett 11
"1"表示泛型类型,带有1个通用参数.
获取字符串的一种方法是使用System.CodeDom,如@LukeH所示:
using System;
using System.CodeDom;
using System.Collections.Generic;
using Microsoft.CSharp;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
using (var p = new CSharpCodeProvider())
{
var r = new CodeTypeReference(typeof(Dictionary<string, int>));
Console.WriteLine(p.GetTypeOutput(r));
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
public static string GetFriendlyTypeName(Type type) {
if (type.IsGenericParameter)
{
return type.Name;
}
if (!type.IsGenericType)
{
return type.FullName;
}
var builder = new System.Text.StringBuilder();
var name = type.Name;
var index = name.IndexOf("`");
builder.AppendFormat("{0}.{1}", type.Namespace, name.Substring(0, index));
builder.Append('<');
var first = true;
foreach (var arg in type.GetGenericArguments())
{
if (!first)
{
builder.Append(',');
}
builder.Append(GetFriendlyTypeName(arg));
first = false;
}
builder.Append('>');
return builder.ToString();
}
Run Code Online (Sandbox Code Playgroud)
这是CLR内部类型名称.
该数字是泛型类型参数的数量,因为类型可以重载.
(Func`1并且Func`2是不同的类型)
由于CLR与C#无关,因此没有内置方法来获取C#样式的类型名称.
| 归档时间: |
|
| 查看次数: |
2048 次 |
| 最近记录: |