NIl*_*nke 23 c# reflection types c#-4.0
Type.GetType("TheClass");
Run Code Online (Sandbox Code Playgroud)
null如果namespace不存在则返回如下:
Type.GetType("SomeNamespace.TheClass"); // returns a Type object
Run Code Online (Sandbox Code Playgroud)
有没有办法避免给出这个namespace名字?
Fr3*_*dan 44
我使用的是搜索所有装入一个辅助方法大会 S代表一类符合指定名称.尽管在我的代码中只预期一个Type结果,但它支持多个.我验证每次使用它时只返回一个结果,并建议你也这样做.
/// <summary>
/// Gets a all Type instances matching the specified class name with just non-namespace qualified class name.
/// </summary>
/// <param name="className">Name of the class sought.</param>
/// <returns>Types that have the class name specified. They may not be in the same namespace.</returns>
public static Type[] getTypeByName(string className)
{
List<Type> returnVal = new List<Type>();
foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
{
Type[] assemblyTypes = a.GetTypes();
for (int j = 0; j < assemblyTypes.Length; j++)
{
if (assemblyTypes[j].Name == className)
{
returnVal.Add(assemblyTypes[j]);
}
}
}
return returnVal.ToArray();
}
Run Code Online (Sandbox Code Playgroud)
toc*_*lle 14
没有必要把事情复杂化。
AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(x => x.GetTypes())
.FirstOrDefault(t => t.Name == "MyTypeName");
Run Code Online (Sandbox Code Playgroud)
使用Where而不是FirstOrDefault获取所有结果。
gdo*_*ica -6
这是该方法期望获得的参数,所以没有。你不能。
typeName:由其命名空间限定的类型名称。
您如何区分具有相同名称但不同命名空间的两个类?
namespace one
{
public class TheClass
{
}
}
namespace two
{
public class TheClass
{
}
}
Type.GetType("TheClass") // Which?!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10642 次 |
| 最近记录: |