反思与自动生成的类型 [英] Reflection and autogenerated types

查看:120
本文介绍了反思与自动生成的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用收益return语句的单一方法的类。嵌套类型自动创建。使用反射与绑定设置为 BindingFlags.DeclaredOnly 标记,我得到这样的输出:




//公共成员从我的课。结果
Test.FileSystemObject..ctor结果
Test.FileSystemObject.GetFiles(DirectoryInfo的目录)结果
Test.FileSystemObject.GetFiles (字符串路径)

  //自动生成的嵌套类。 
Test.FileSystemObject +下;的GetFiles> d__4..ctor
Test.FileSystemObject +下; GetFiles的方式> d__4&所述;> 3__directory
Test.FileSystemObject +下; GetFiles的方式> d__4&下;> 4__this
Test.FileSystemObject +下;的GetFiles> d__4&下;目录> 5__7
Test.FileSystemObject +下; GetFiles的方式> d__4&所述;文件> 5__8
Test.FileSystemObject + &所述; GetFiles的方式> d__4&所述; FSO> 5__6
Test.FileSystemObject +下; GetFiles的方式> d__4&所述; I> 5__9
Test.FileSystemObject +下; GetFiles的方式> d__4&所述未处理的> 5__5
Test.FileSystemObject + LT; GetFiles的> d__4.directory




我如何确定一个类型是否通过 assembly.GetTypes(BindingsFlags)返回就是这样一个自动生成的类型?我在寻找一个简单的方法来排除这些。


解决方案

您可以测试类型具有 [编译器生成] 属性:

 如果(type.GetCustomAttribute(typeof运算(CompilerGeneratedAttribute),真) != NULL)
{

}

另外,您可以检查名称包含字符不会在用户代码中有效。


I have a class with a single method that uses a "yield" return statement. A nested type is automatically created. Using reflection with binding flags set to BindingFlags.DeclaredOnly, I get this output:

// Public members from my class.
Test.FileSystemObject..ctor
Test.FileSystemObject.GetFiles(DirectoryInfo directory)
Test.FileSystemObject.GetFiles(String path)

// Auto generated nested class.  
Test.FileSystemObject+<GetFiles>d__4..ctor  
Test.FileSystemObject+<GetFiles>d__4.<>3__directory  
Test.FileSystemObject+<GetFiles>d__4.<>4__this  
Test.FileSystemObject+<GetFiles>d__4.<directories>5__7  
Test.FileSystemObject+<GetFiles>d__4.<files>5__8  
Test.FileSystemObject+<GetFiles>d__4.<FSO>5__6  
Test.FileSystemObject+<GetFiles>d__4.<i>5__9  
Test.FileSystemObject+<GetFiles>d__4.<unprocessed>5__5  
Test.FileSystemObject+<GetFiles>d__4.directory

How can I determine whether a type returned by assembly.GetTypes(BindingsFlags) is such an auto generated type? I'm looking for a simple way to exclude these.

解决方案

You can test if the type has the [CompilerGenerated] attribute:

if (type.GetCustomAttribute(typeof(CompilerGeneratedAttribute), true) != null)
{
    ...
}

Alternatively, you can check if the name contains characters that wouldn't be valid in user code.

这篇关于反思与自动生成的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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