确定类型是否为匿名类型 [英] Determining whether a Type is an Anonymous Type

查看:30
本文介绍了确定类型是否为匿名类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 3.0 中,是否可以确定 Type 的实例是否代表匿名类型?

In C# 3.0, is it possible to determine whether an instance of Type represents an Anonymous Type?

推荐答案

即使匿名类型是普通类型,您也可以使用一些启发式方法:

Even though an anonymous type is an ordinary type, you can use some heuristics:

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# 类名的情况下生成的 - 为此使用正则表达式).

Another good heuristic to be used is if the class name is a valid C# name (anonymous type are generated with no valid C# class names - use regular expression for this).

这篇关于确定类型是否为匿名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆