【发布时间】:2010-12-11 15:54:41
【问题描述】:
在 C# 3.0 中,是否可以确定 Type 的实例是否代表匿名类型?
【问题讨论】:
标签: c# .net .net-3.5 c#-3.0 anonymous-types
在 C# 3.0 中,是否可以确定 Type 的实例是否代表匿名类型?
【问题讨论】:
标签: c# .net .net-3.5 c#-3.0 anonymous-types
即使匿名类型是普通类型,您也可以使用一些启发式方法:
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"); 不是真的。
匿名类型对象的属性
对于我的特定应用程序,如果命名空间为 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;
}
【讨论】:
在元数据和 CLR 中没有匿名类型这样的术语。匿名类型只是编译器功能。
【讨论】:
了解您为什么想知道这一点可能会有所帮助。如果您执行以下操作:
var myType = new { Name = "Bill" };
Console.Write( myType.GetType().Name );
...您会看到类似“f__AnonymousType0`1”的输出作为类型名称。根据您的要求,您可以假设以 开头、包含“AnonymousType”和反引号字符的类型就是您要查找的类型。
【讨论】:
似乎匿名类型会在Type = "<Anonymous Type>" 的位置加上DebuggerDisplayAttribute。
编辑:但仅当您在调试模式下编译时。该死。
【讨论】: