识别 C# IList 中对象的类
我有一个 IList 变量,其中包含 1 - N 个 myObject 条目。每个条目可以是 myObject 或其任何子对象(派生类对象)的实例。在对 IList 执行 foreach 时,如何识别 IList 的每个成员属于哪种类型的对象?
foreach(myObject anObject in myList)
{
if(anObject is of type ???)
}
I have an IList variable which contains 1 - N entries of myObject. Each entry can be an instance of myObject or any of it's child objects (derived class objects). When doing a foreach over the IList, how can I identify which type of object each member of the IList is?
foreach(myObject anObject in myList)
{
if(anObject is of type ???)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
看一下is 运算符 。
Take a look at the is operator.
您可以使用
anObject is MyObject
或者
也可以使用
baseType.IsAssignableFrom(type)
来确定类型是否可以从给定的基类型派生You could make use of
anObject is MyObject
or
You can also make use of
baseType.IsAssignableFrom(type)
to determine if a type can be derived from a given base type我不是一个 .NET 开发人员,但在 Java 中,有一个名为 instanceof 的运算符,它将检查对象是否是某个类的实例。
查看此链接,它与对象的 typeid 有关,我认为这就是您正在寻找的伙伴。
http://msdn.microsoft.com/en-us/库/b2ay8610(vs.71).aspx
I'm not much of a .NET developer but in Java there's an operator called instanceof that will check if the object is an instance of a certain class.
Check this link out, it has to do with the typeid of an object, I think that's what you're looking for mate.
http://msdn.microsoft.com/en-us/library/b2ay8610(vs.71).aspx
如果您想询问每个实例的类型,请这样做:
If you want to ask for the type of each instance do it like this:
如果您的 OO 结构设计正确,您确实不需要知道 - 无论您想对对象做什么,都可以使用适当的实现来完成,无论它是什么类型。
话虽如此,您可以通过调用来获取任何对象的类型:
您可以将该类型与另一个特定类型进行比较,例如:
is
运算符可能会给您带来麻烦,具体取决于您的情况,因为如果您正在检查某个东西是否是父类,即使它确实是一个子类,这也是正确的。例如:此
if
将为Foo
或Bar
对象返回 true。If your OO structure is designed properly, you really shouldn't need to know - whatever you want to do with the object can be done using the appropriate implementation, regardless of which type it is.
With that said, you can get the type of any object by calling:
And you can compare that type to another specific type, like:
The
is
operator can get you in trouble, depending on your scenario, since it will be true if you are checking if something is a parent class, even if it really is a child. For example:This
if
will return true for eitherFoo
orBar
objects.