C# 我可以从中获取类的类型吗?
我正在尝试构建一个可以确定自己类型的基类,但我不确定如何去做,很明显,this.GetType在typeOf中不起作用,所以有没有办法获取当前类的类类型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
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()代码>应该可以正常工作