检查对象是否属于同一类型

发布于 2024-10-04 05:24:51 字数 400 浏览 3 评论 0原文

您好,我需要知道如何在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

九歌凝 2024-10-11 05:24:51

您可以使用 is 运算符

if (data is Person)
{
    // `data` is an instance of Person
}

另一种可能性是使用 as 运算符

var person = data as Person;
if (person != null)
{
    // safely use `person` here
}

或者,从 C# 7 开始,使用 结合了上述两者的 is 运算符的模式匹配形式:

if (data is Person person)
{
    // `data` is an instance of Person,
    // and you can use it as such through `person`.
}

You could use the is operator:

if (data is Person)
{
    // `data` is an instance of Person
}

Another possibility is to use the as operator:

var person = data as Person;
if (person != null)
{
    // safely use `person` here
}

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`.
}
━╋う一瞬間旳綻放 2024-10-11 05:24:51

这完全取决于你想要什么。使用 isas (如 Darin 的回答所示)将告诉您 data 是否引用 Person 的实例或子类型。这是最常见的形式(尽管如果您可以在不需要它的情况下进行设计,那就更好了) - 如果这就是您所需要的,达林的答案就是使用的方法。

但是,如果您需要精确匹配 - 如果您不想在 data 引用从 Person< 派生的某个类的实例时执行特定操作/code>,仅对于 Person 本身,您需要这样的东西:

if (data.GetType() == typeof(Person))

这是相对罕见的 - 此时绝对值得质疑您的设计。

It depends on exactly what you're after. Using is or as (as shown in Darin's answer) will tell you if data refers to an instance of Person 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 from Person, only for Person itself, you'll need something like this:

if (data.GetType() == typeof(Person))

This is relatively rare - and it's definitely worth questioning your design at this point.

心房敞 2024-10-11 05:24:51

让我们一次一步地解决这个问题。第一步是必需的,接下来的两个是可选的,但建议执行。

第一次更正(这是必需的)确保您没有将某种类型的对象与 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)!

第二,简化这到:

if (data is Person) ... // this has (almost) the same meaning as the above;
                        // in your case, it's what you need.

第三,完全摆脱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();
    }
}

如您所见,条件代码已转移到 Base_DataCheck 方法中类及其派生类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:

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)!

Second, simplify this to:

if (data is Person) ... // this has (almost) the same meaning as the above;
                        // in your case, it's what you need.

Third, get rid of the if statement altogether! This is done by employing polymorphism (or, more precisely, method overriding) e.g. as follows:

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();
    }
}

As you see, the conditional code has been shifted into a Check method of the Base_Data class and its derived class Person. No more need of such a type-checking if statement!

终难遇 2024-10-11 05:24:51

这个问题的意图有点不清楚,但我发现这个问题是在寻找一种方法来检查两个对象是否属于同一类型。这是我的解决方案以及所有通过的一些测试:

using NUnit.Framework;

[TestFixture]
public class TypeEqualityChecks
{
    class Base_Data { }

    class Person : Base_Data { }
    class Phone  : Base_Data { }

    class AnotherClass
    {
        public static bool CheckObjects(Base_Data d1, Base_Data d2) {
            return d1.GetType() == d2.GetType();
        }
    }
    
    [Test]
    public static void SameTypesAreEqual() {
        Base_Data person1 = new Person();
        Base_Data person2 = new Person();
        Assert.IsTrue(AnotherClass.CheckObjects(person1, person2));
    }
    
    [Test]
    public static void DifferentActualTypesAreNotEqual() {
        Base_Data person = new Person();
        Base_Data phone = new Phone();
        Assert.IsFalse(AnotherClass.CheckObjects(person, phone));
    }
    
    [Test]
    public static void BaseTypeAndChildTypeAreNotEqual() {
        Base_Data baseData = new Base_Data();
        Base_Data person = new Person();
        Assert.IsFalse(AnotherClass.CheckObjects(baseData, person));
    }
}

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:

using NUnit.Framework;

[TestFixture]
public class TypeEqualityChecks
{
    class Base_Data { }

    class Person : Base_Data { }
    class Phone  : Base_Data { }

    class AnotherClass
    {
        public static bool CheckObjects(Base_Data d1, Base_Data d2) {
            return d1.GetType() == d2.GetType();
        }
    }
    
    [Test]
    public static void SameTypesAreEqual() {
        Base_Data person1 = new Person();
        Base_Data person2 = new Person();
        Assert.IsTrue(AnotherClass.CheckObjects(person1, person2));
    }
    
    [Test]
    public static void DifferentActualTypesAreNotEqual() {
        Base_Data person = new Person();
        Base_Data phone = new Phone();
        Assert.IsFalse(AnotherClass.CheckObjects(person, phone));
    }
    
    [Test]
    public static void BaseTypeAndChildTypeAreNotEqual() {
        Base_Data baseData = new Base_Data();
        Base_Data person = new Person();
        Assert.IsFalse(AnotherClass.CheckObjects(baseData, person));
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文