确定一个类型是一个匿名类型是一个、类型

2023-09-07 02:24:52 作者:基情澎湃

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