在 C# 3.0 中,是否有可能确定一个
Type
实例表示的是匿名类型?Type
实例表示的是匿名类型?尽管匿名类型是普通类型,但您可以使用一些启发式方法:
public static class TypeExtension {
public static Boolean IsAnonymousType(this Type type) {
Boolean hasCompilerGeneratedAttribute = type.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Count() > 0;
Boolean nameContainsAnonymousType = type.FullName.Contains("AnonymousType");
Boolean isAnonymousType = hasCompilerGeneratedAttribute && nameContainsAnonymousType;
return isAnonymousType;
}
}
另一个好的启发式方法是,如果类名是有效的 C# 名称(匿名类型生成的名称不符合有效的 C# 类名 - 使用正则表达式来处理)。
type.FullName.Contains("AnonymousType")
不成立。 - albertjan匿名类型对象的属性
对于我的特定应用程序而言,如果命名空间为 null,则可以推断该类型为匿名类型,因此检查命名空间是否为 null 可能是最便宜的检查。
在C#语言中没有一种构造可以让你说“这是一个匿名类型”。你可以使用简单的启发式方法来近似判断一个类型是否为匿名类型,但是可能会被手动编写IL代码的人或使用某些字符(如>和<)作为标识符的语言所欺骗。
public static class TypeExtensions {
public static bool IsAnonymousType(this Type t) {
var name = t.Name;
if ( name.Length < 3 ) {
return false;
}
return name[0] == '<'
&& name[1] == '>'
&& name.IndexOf("AnonymousType", StringComparison.Ordinal) > 0;
}
可能知道你为什么想知道这个。如果你执行以下操作:
var myType = new { Name = "Bill" };
Console.Write( myType.GetType().Name );
...你会看到类名输出为"<>f__AnonymousType0`1"。根据你的需求,你可以假设以"<>"开头,包含"AnonymousType"和反引号字符的类型就是你要找的。
匿名类型似乎会被添加一个DebuggerDisplayAttribute
,其中Type = "<Anonymous Type>"
。
编辑:但只有在调试模式下编译时才会添加。糟糕。