简体   繁体   中英

compare object to class

I'm trying to compare a class type passed through as an object to the class type on the other side where the method is.

How can I do this?

I have this so far.

The one side:

TechToday techToday = new TechToday();
SoftwareRevolution softwareRevolution = new SoftwareRevolution();

Subcriber s1 = new Subcriber();
s1.Subcribe(techToday);
s1.Subcribe(softwareRevolution);

The other side:

class Subcriber
{
    TechToday tt = new TechToday();
    SoftwareRevolution sr = new SoftwareRevolution();

    public void Subcribe(Object s)
    {
        if(s==tt)
            new ConsoleObserver(s);
        else                
            new ConsoleOutput(s);

    }

}

You can use is operator to check if object is of that particular type like:

if(s is TechToday)
        new ConsoleObserver(s);

or you can do something like:

if(s.GetType() == typeof(TechToday))

if you are looking to do equality of objects then you will need to check first the type of it and then cast the reference to that specific type and then check for equality something like:

if(s is TechToday)
{
   TechToday tt2 = s as TechToday;
   if(tt2 == tt)
       new ConsoleObserver(tt2);
}

or you could also do it like:

TechToday tt2 = s as TechToday;
if(tt2 == tt)
    new ConsoleObserver(tt2);

Another option is using the new feature of C# 7 pattern matching :

if (s is TechToday tt2)
{
   if(tt2 == tt)
      new ConsoleObserver(tt2);
}

I'd suggest to use overloads if possible:

class Subcriber
{
    public void Subcribe(TechToday s)
    {
        new ConsoleObserver(s);
    }

    public void Subcribe(SoftwareRevolution s)
    {               
        new ConsoleOutput(s);
    }

}

If you have to stay with object in the signature of Subscribe , you probably want to use something along

if( s is TechToday ) { new ConsoleObserver(s); }

But after all, this does not make much sense , because as is, the created objects will go out of scope immediately after leaving Subscribe .

You can use the is operator:

class Subcriber
{
    public void Subcribe(Object s)
    {
        if(s is TechToday)
            new ConsoleObserver(s);
        else                
            new ConsoleOutput(s);

    }
}

However using "as" might be better:

class Subcriber
{
    public void Subcribe(Object s)
    {
        var tt = s as TechToday; 
        if(tt!=null)
           // unlike above 
           // value passed to ConsoleObserver is TechToday
           // casted already

            new ConsoleObserver(tt); 
        else                
            new ConsoleOutput(s);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM