开发者

Best way to test if an object is in a set of objects?

开发者 https://www.devze.com 2022-12-28 08:02 出处:网络
I\'m trying to avoid using a long else if statement. Lets say I have an object and I want to test if it\'s of type ClassA, ClassB, Cla开发者_如何学JAVAssC, etc..?

I'm trying to avoid using a long else if statement.

Lets say I have an object and I want to test if it's of type ClassA, ClassB, Cla开发者_如何学JAVAssC, etc..?

What is a clean way of doing this?


Often, when you have to test an object's type, it can be a sign that there's something wrong with your design. Object oriented programming offers us an opportunity to avoid these sorts of constructs via polymorphism.

Wouldn't it be better if A,B and C implemented the bodies of your proposed if statements under a base class interface such that you don't have to test upstream?

For instance:

abstract class A
{
    public virtual void SomeBehavior()
    {
        Console.WriteLine("default behavior");
    }
}

class B:A
{
    public override void SomeBehavior()
    {
         Console.WriteLine("type specific behavior");
    }
}

class C:A
{
    public override void SomeBehavior()
    {
         Console.WriteLine("different behavior");
    }
}

class D:A{}

void Main()
{
    IEnumerable<A> myCollection=new A[]{new B(),new C(),new D()};
    foreach(A item in myCollection)
    {
        item.SomeBehavior();
    }
}


Something like..

if (new[] { typeof(ClassA), typeof(ClassB), typeof(ClassC) }.Contains(obj.GetType()))

?

And obviously if you have a lot of types and are seeing bad performance, then throw it into a dictionary and use ContainsKey.


have a list of types you want to test against then ask the list if it "Contains" the type of object you have?

Also, not sure why you are doing that.

But perhaps something like IsAssignableFrom ( http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx ) is what you are looking for?


myobject.GetType() will yield the objects type to test for equality against other types.

0

精彩评论

暂无评论...
验证码 换一张
取 消