是否可以检查一个类型是否是命名空间的一部分,而不使用经过编码的字符串?
我试图做一些像:
Type type = typeof(System.Data.Constraint); if(type.Namespace == System.Data.ToString()) {...}
要么
Type type = typeof(System.Data.Constraint); if(type.Namespace == System.Data) {...}
避免
Type type = typeof(System.Data.Constraint); if(type.Namespace == "System.Data") {...}
这些例子不编译,但应该提出我想要实现的想法.
我不能使用nameof(System.Data),因为它只返回“Data”.
我想找到一种方法来检查一个类是否是命名空间的一部分,而不需要在字符串中具有该命名空间.
解决方法
您可以在要执行检查的命名空间中定义它:
static class Namespace { public static bool Contains<T>() => typeof (T).Namespace == typeof (Namespace).Namespace; }
例如:
namespace My.Inner { static class Namespace { public static bool Contains<T>() => typeof (T).Namespace == typeof (Namespace).Namespace; } }
两种类型作为测试用例:
namespace My { class SomeTypeA { } } namespace My.Inner { class SomeTypeB { } }
以下是用法:
Console.WriteLine(My.Inner.Namespace.Contains<SomeTypeA>()); // False Console.WriteLine(My.Inner.Namespace.Contains<SomeTypeB>()); // True