Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我可以从中获取类的类型吗?_C# - Fatal编程技术网

C# 我可以从中获取类的类型吗?

C# 我可以从中获取类的类型吗?,c#,C#,我正在尝试构建一个可以确定自己类型的基类,但我不确定如何去做,很明显,this.GetType在typeOf中不起作用,所以有没有办法获取当前类的类类型 class BassClass { public string GetValueofSomething() { Type type = typeof(this.GetType()); //this obviously doesn't work type = typeOf(BaseClass); //works fine

我正在尝试构建一个可以确定自己类型的基类,但我不确定如何去做,很明显,this.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 ""
}
}
应该可以正常工作。

GetType()
返回一个
类型
,因此不需要
类型

class BassClass
{
     public string GetValueOfSomething()
     {
        Type type = this.GetType();
        MemberInfo[] members = type.GetMembers();
        ...
    }
}
Type type = this.GetType();   //gets the actual type of this object

但您确实应该避免使用反射访问派生类的成员,这是可能的。声明派生类可以重写的抽象或虚拟成员:

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

     public string GetValueOfSomething()
     {
         return this.Something;
     }
}

您不需要的
类型为

class BassClass
{
     public string GetValueOfSomething()
     {
        Type type = this.GetType();
        MemberInfo[] members = type.GetMembers();
        ...
    }
}
Type type = this.GetType();   //gets the actual type of this object

注意
typeof
操作符与
System.Object.GetType
方法的不同用法:

obj.GetType()
对对象实例
obj
调用
GetType
,并返回该对象的动态(运行时)类型。(您可以认为这只能在运行时解决。)

typeof(T)
typeof
运算符用于类型名
T
。(您可以认为这已经在编译时解决了。)


你只需要其中一个;您永远不需要组合
typeof
GetType
。因此,在您的例子中,只需
Type Type=this.GetType()应该可以正常工作