[英]Issue Related to Assembly.GetExecutingAssembly().GetTypes() in C#
On my website.在我的网站上。 I have added a class file in
App_Code
containing 5 public classes into one NameSpace.我在
App_Code
中添加了一个包含 5 个公共类的类文件到一个 NameSpace 中。
I want to get all class names containing in a particular namespace.我想获取包含在特定命名空间中的所有类名。
In default.aspx.cs file i have added.在我添加的 default.aspx.cs 文件中。
var q = from t in Assembly.GetExecutingAssembly().GetTypes()
where t.IsClass && t.Namespace == "Sample"
q.ToList().ForEach(t => Console.WriteLine(t.Name));
But I didn't find Sample namespace in Assembly.GetExecutingAssembly().GetTypes()
how do I access the 'Sample'
namespce in above code?但是我没有在
Assembly.GetExecutingAssembly().GetTypes()
找到 Sample namespace 我如何访问上面代码中的'Sample'
命名空间?
Thanks谢谢
In default.aspx.cs file i have added
在我添加的 default.aspx.cs 文件中
That's the problem.那就是问题所在。 When you have a website (in contrast to a web application), all code that you put inside
App_Code
is compiled dynamically at runtime in a separate assembly.当您拥有一个网站时(与 Web 应用程序相反),您放入
App_Code
所有代码都会在运行时在单独的程序集中动态编译。 So when you write Assembly.GetExecutingAssembly()
you are basically getting the assembly that was generated for your default.aspx
WebForm which is different than the assembly containing the code in App_Code
.因此,当您编写
Assembly.GetExecutingAssembly()
您基本上获得了为default.aspx
WebForm 生成的程序集,它与包含App_Code
中的代码的程序集不同。 You could loop through all referenced assemblies in the project to look for types.您可以遍历项目中所有引用的程序集以查找类型。
To get this list of assemblies you could use the GetAssemblies method on the current application domain.要获取此程序集列表,您可以在当前应用程序域上使用GetAssemblies方法。
Another possibility is to use some known type that you know was contained in the App_Code
folder in order to get its assembly:另一种可能性是使用您知道包含在
App_Code
文件夹中的某些已知类型来获取其程序集:
var assembly = typeof(Some_Type_That_Is_Declared_In_App_Code).Assembly;
var q =
from t in assembly.GetTypes()
where t.IsClass && t.Namespace == "Sample"
select t;
I think the problem here might be due to the fact that this code is being executed in a temporary assembly created from your codebehind files.我认为这里的问题可能是由于此代码是在从代码隐藏文件创建的临时程序集中执行的。
To check this:要检查这个:
var q = from t in Assembly.GetExecutingAssembly().GetTypes() where t.IsClass select t; q.ToList().ForEach(t => Console.WriteLine(t.Namespace));
typeof(Sample.Class1).Assembly
typeof(Sample.Class1).Assembly
or... just read @Darin's answer... I must learn to type faster!或者...只需阅读@Darin 的回答...我必须学会更快地打字!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.