您好我需要知道如何在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.
}
}
}
Run Code Online (Sandbox Code Playgroud)
Dar*_*rov 86
您可以使用is运算符:
if (data is Person)
{
// `data` is an instance of Person
}
Run Code Online (Sandbox Code Playgroud)
另一种可能性是使用as运算符:
var person = data as Person;
if (person != null)
{
// safely use `person` here
}
Run Code Online (Sandbox Code Playgroud)
或者,从C#7开始,使用结合上述两者的is运算符的模式匹配形式:
if (data is Person person)
{
// `data` is an instance of Person,
// and you can use it as such through `person`.
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 25
这取决于你究竟是在追求什么.使用is或as(如Darin的答案所示)将告诉您是否data引用了一个实例Person 或子类型.这是最常见的形式(尽管如果你可以设计远离需要它,那就更好了) - 如果这就是你所需要的,那么Darin的答案就是使用它的方法.
但是,如果你需要一个完全匹配 - 如果你不想采取特定的动作,如果data引用某个类的实例Person,只是为了Person它自己,你需要这样的东西:
if (data.GetType() == typeof(Person))
Run Code Online (Sandbox Code Playgroud)
这是相对罕见的 - 在这一点上绝对值得质疑你的设计.
让我们一步一步解决这个问题.第一步是必需的,接下来的两个是可选的,但建议.
第一次校正(这是必需的)确保您不会将某种类型的对象与类型的对象进行比较System.Type:
if (data.GetType().Equals(typeof(Person))) ...
// ^^^^^^^^^^
// add this to make sure you're comparing Type against Type, not
// Base_Data against Type (which caused the type-check error)!
Run Code Online (Sandbox Code Playgroud)
其次,将其简化为:
if (data is Person) ... // this has (almost) the same meaning as the above;
// in your case, it's what you need.
Run Code Online (Sandbox Code Playgroud)
第三,if完全摆脱声明!这是通过使用多态(或更确切地说,方法重写)来完成的,例如如下:
class Base_Data
{
public virtual void Check() { ... }
}
class Person : Base_Data
{
public override void Check()
{
... // <-- do whatever you would have done inside the if block
}
}
class AnotherClass
{
public void CheckData(Base_Data data)
{
data.Check();
}
}
Run Code Online (Sandbox Code Playgroud)
正如你看到的,有条件的代码已经被转移到Check了方法Base_Data类及其派生类Person.不再需要这样的类型检查if声明!
| 归档时间: |
|
| 查看次数: |
62510 次 |
| 最近记录: |