本文介绍了检查对象是否为相同类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,我需要知道如何在C#中检查相同类型的对象.
Hello I need to know how to check if the object of the same type in 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.
}
}
}
推荐答案
您可以使用 is
运算符:
You could use the is
operator:
if (data is Person)
{
// `data` is an instance of Person
}
另一种可能性是使用 as
运算符:
Another possibility is to use the as
operator:
var person = data as Person;
if (person != null)
{
// safely use `person` here
}
或者,从 C# 7 开始,使用 结合了以上两个的is
操作符的模式匹配形式:
Or, starting with C# 7, use a pattern-matching form of the is
operator that combines the above two:
if (data is Person person)
{
// `data` is an instance of Person,
// and you can use it as such through `person`.
}
这篇关于检查对象是否为相同类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!