我可以从中获得类的类型吗?

Jas*_*ter 2 c#

我正在尝试构建一个可以确定自己类型的基类,但我不知道该怎么做,显然这个.GetType在typeOf中不起作用,所以有没有办法获取类的类型目前的课程?

class BassClass {
public string GetValueofSomething() {
    Type type = typeof(this.GetType()); //this obviously doesn't work
    type = typeOf(BaseClass);  //works fine
    MemberInfo[] members = type.GetMembers();
    //Other stuff here
    return ""
}
}
Run Code Online (Sandbox Code Playgroud)

dtb*_*dtb 6

GetType()返回a Type,所以不需要typeof:

class BassClass
{
     public string GetValueOfSomething()
     {
        Type type = this.GetType();
        MemberInfo[] members = type.GetMembers();
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

但是你应该真的避免使用反射来访问派生类的成员.声明派生类可以覆盖的抽象或虚拟成员:

class BaseClass
{
     protected virtual string Something
     {
         get { return ""; }
     }

     public string GetValueOfSomething()
     {
         return this.Something;
     }
}
Run Code Online (Sandbox Code Playgroud)