日期:2014-05-17  浏览次数:20746 次

如何通过反射得到所在的命名空间与类的名称
//如下代码:
namespace MyNameSpace
{
    public class MyClass
    {
        public void Test()
        {
            //下面是是死的。 如何自动获取到代码所在的命名空间与所在类名呢?
            String CurrNameSpaceAndClassName = "MyNameSpace.MyClass";
            Type type = Type.GetType(CurrNameSpaceAndClassName);
            //
        }
    }
}

------解决方案--------------------
Type type = typeof(MyClass);
string name = type.FullName;
------解决方案--------------------
Type type = new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().DeclaringType;

------解决方案--------------------
System.Reflection.MethodBase.GetCurrentMethod().ReflectedType

------解决方案--------------------
this.GetType()不就可以了。
------解决方案--------------------
this.GetType()就可以获得当前的类的信息了,你何必用字符串来处理?
------解决方案--------------------
MethodBase.GetCurrentMethod().DeclaringType
------解决方案--------------------
public IEnumerable GetNearClass()
        {
            var myType = this.GetType();
            var ns = myType.Namespace;
            List<Type> types= new List<Type>();
            foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies())
            {
                foreach (var type in assembly.GetTypes())
                {
                    if (type.Namespace == ns)
                        types.Add(type);
                }
            }
           
            return types;
        }

试试吧