检查对象是否属于同一类型
您好,我需要知道如何在 C# 中检查相同类型的对象。
场景:
class Base_Data{}
class Person : Base_Data { }
class Phone : Base_data { }
class AnotherClass
{
public void CheckObject(Base_Data data)
{
if (data.Equals(Person.GetType()))
{ //<-- Visual Studio 2010 gives me error, says that I am using 'Person' is a type and not a variable.
}
}
}
Hello I need to know how to check if the object of the same type in C#.
Scenario:
class Base_Data{}
class Person : Base_Data { }
class Phone : Base_data { }
class AnotherClass
{
public void CheckObject(Base_Data data)
{
if (data.Equals(Person.GetType()))
{ //<-- Visual Studio 2010 gives me error, says that I am using 'Person' is a type and not a variable.
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
is
运算符:另一种可能性是使用
as
运算符:或者,从 C# 7 开始,使用 结合了上述两者的
is
运算符的模式匹配形式:You could use the
is
operator:Another possibility is to use the
as
operator:Or, starting with C# 7, use a pattern-matching form of the
is
operator that combines the above two:这完全取决于你想要什么。使用
is
或as
(如 Darin 的回答所示)将告诉您data
是否引用Person
的实例或子类型。这是最常见的形式(尽管如果您可以在不需要它的情况下进行设计,那就更好了) - 如果这就是您所需要的,达林的答案就是使用的方法。但是,如果您需要精确匹配 - 如果您不想在
data
引用从Person< 派生的某个类的实例时执行特定操作/code>,仅对于
Person
本身,您需要这样的东西:这是相对罕见的 - 此时绝对值得质疑您的设计。
It depends on exactly what you're after. Using
is
oras
(as shown in Darin's answer) will tell you ifdata
refers to an instance ofPerson
or a subtype. That's the most common form (although if you can design away from needing it, that would be even better) - and if that's what you need, Darin's answer is the approach to use.However, if you need an exact match - if you don't want to take the particular action if
data
refers to an instance of some class derived fromPerson
, only forPerson
itself, you'll need something like this:This is relatively rare - and it's definitely worth questioning your design at this point.
让我们一次一步地解决这个问题。第一步是必需的,接下来的两个是可选的,但建议执行。
第一次更正(这是必需的)确保您没有将某种类型的对象与
System.Type
类型的对象进行比较:第二,简化这到:
第三,完全摆脱
if
语句!这是通过使用多态性(或更准确地说,方法重写)来完成的,如下所示:如您所见,条件代码已转移到
Base_Data
的Check
方法中类及其派生类Person
。不再需要这样的类型检查if
语句!Let's fix this one step at a time. The first step is required, the next two are optional but suggested.
The first correction (which is required) makes sure that you're not comparing an object of some type with an object of type
System.Type
:Second, simplify this to:
Third, get rid of the
if
statement altogether! This is done by employing polymorphism (or, more precisely, method overriding) e.g. as follows:As you see, the conditional code has been shifted into a
Check
method of theBase_Data
class and its derived classPerson
. No more need of such a type-checkingif
statement!这个问题的意图有点不清楚,但我发现这个问题是在寻找一种方法来检查两个对象是否属于同一类型。这是我的解决方案以及所有通过的一些测试:
The intention of the question is a bit unclear but I found this question where looking for a way to check if 2 objects are of the same type. Here's my solution for that and some tests that all pass: