How do I determine whether the types of two objects are compatible?

前端 未结 4 1186
孤城傲影
孤城傲影 2021-01-15 08:12

I have a generic function that I want to know how to write.

List something;

public int countItems(List Items)
{
    // He         


        
相关标签:
4条回答
  • 2021-01-15 08:29

    The question is poorly stated and more than a little vague, but this might do it:

    using System.Linq;
    
    public int countItems<T>(List<T> Items)
    {
        return Items.OfType<Something>().Where(thing => thisOneCounts(thing)).Count();
    }
    
    0 讨论(0)
  • 2021-01-15 08:44

    I think what you want is to use the IComparable interface.

    Another tool you may want to use is operator overloading, so that you can define how under what circumstances two objects are equal.

    0 讨论(0)
  • 2021-01-15 08:50
    if (something.GetType() == items.GetType()) ...
    

    This will compare the types of the actual objects.

    0 讨论(0)
  • 2021-01-15 08:53

    do you mean:

    if(typeof(T) == typeof(Something)) {...}
    

    ?

    Note that having generics depend hugely on the T (and act differently) may mean what you are trying to do isn't actually very generic...

    0 讨论(0)
提交回复
热议问题