避免在Type.GetType()中给出命名空间名称

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)

  • +1回答问题,而不是堆积在上面的火焰战争. (20认同)
  • 另一个答案是来自知道而不是不使用命名空间bla bla :)的人来回答 (2认同)

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)

  • @gdoron,您需要查看用户实际想要什么,而不仅仅是问题标题的字面含义。就像我问我是否可以喝西瓜,你只是回答“你不能”,但随后 Fr33dan 出现并说“如果你把它切成丁并扔进 Nutribullet 中,你就可以” - 这就是我实际上的意思后。我认为可以肯定地说,在这种情况下,用户只是想要某种方式来获取类型,而不必指定名称空间。 (9认同)
  • @NIleshLanke,我希望您意识到 Microsoft 并没有根据 **您的** 需求来设计 .NET 框架,但它的架构是为了在更广泛的场景中使用。例如,在两个不同的命名空间中具有相同的类名的场景。 (4认同)
  • @gdoron,阅读此http://stackoverflow.com/help/how-to-answer,尤其是有关“回答问题”的部分 (4认同)
  • @gdoron,不,你没有。上面的答案字面意思告诉你如何去做。 (3认同)
  • @gdoron,当接受的答案表明它可以时,为什么这篇文章中坚持认为它不可能? (2认同)