如何从另一个派生类获取派生类的类型
我有(伪)代码:
public class GlobalClass
{
public GlobalClass()
{
var x = this.GetType().Name // Returns "Channels"
// WHAT TO DO HERE?
}
}
public class BaseClass
{
public string Title { get; set; }
}
并使用此代码:
public class Channels : GlobalClass
{
public Channels()
{
}
public class Channel : BaseClass
{
}
}
注释所在的位置(// WHAT TO DO HERE?),我想获取 BaseClass 的运行时类型, 我的示例代码中的其中位置应返回 Channel
。
我对不同的方法持开放态度,但前提是它附有我为什么应该更改代码的解释。
I have the (pseudo) code:
public class GlobalClass
{
public GlobalClass()
{
var x = this.GetType().Name // Returns "Channels"
// WHAT TO DO HERE?
}
}
public class BaseClass
{
public string Title { get; set; }
}
And using this code:
public class Channels : GlobalClass
{
public Channels()
{
}
public class Channel : BaseClass
{
}
}
Where the comment is (// WHAT TO DO HERE?), I want to get the runtime type of BaseClass,
where in my sample code should return Channel
.
I am open to different approaches, but only if it's accompanied with an explanation why I should change the code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为你在这里需要一个通用类,例如:
I think you need a generic class here, something like:
您可以像这样使用反射:
...
另请参阅 Stack Overflow 问题程序集中的类列表 。
You can use reflection like this:
...
See also Stack Overflow question List of classes in an assembly.
是
运算符就是为了这个目的。getType()
类方法也可以使用>类型
。is
operator is just for that purpose.getType()
method with classType
can also be used.要获取任何内容的运行时类型,您首先需要一个对象实例来获取类型。因此,根据您给定的结构,这是不可能的。
有两种可能的方法:
将
BaseClass
参数添加到 GlobalClass 的构造函数中:直接将类型传递给构造函数:
如果由于某种原因结构不允许此处使用泛型(如 Danny Chen 建议),我个人更喜欢第二种方法,因为它不需要实际实例。
To get the runtime type of anything, you first need an object instance to get the type from. So with your given structure, that's not possible.
There are two possible approaches:
Add a
BaseClass
parameter to the constructor of your GlobalClass:Pass the type to the constructor directly:
If the structure for some reason doesn't allow generics here (as Danny Chen suggested), I'd personally prefer the second approach, since that doesn't need an actual instance.