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

问题描述

在C#3.0,是可以确定的键入重$ P $实例是否psents匿名类型?

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#类名生成匿名类型 - 使用常规EX pression此)。

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).

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

09-05 10:14
查看更多