C# Multiple generic constraints

后端 未结 7 1009
野性不改
野性不改 2020-12-17 09:17

I was wondering if it is possible to add multiple generic constraints?

I have an Add method that takes an Object (Either Email, Phone or Address), so i was thinking

相关标签:
7条回答
  • 2020-12-17 10:03

    Like others have said, in your specific case you should use inheritance or method overloading instead of generics. However, if you do need to create a generic method with multiple constraints then you can do it like this.

    public void Foo<T>() where T : Bar, IBaz, new()
    {
        // Your code here
    }
    
    0 讨论(0)
  • 2020-12-17 10:05

    You can't do that. Why not just have three methods and let the compiler do the hard work for you?

    public void Add(Address address) { m_Address.Add(address); }
    public void Add(Email email) { m_Email.Add(email); }
    public void Add(Phone phone) { m_Phone.Add(phone); }
    
    0 讨论(0)
  • 2020-12-17 10:11

    CLR does not allow multiple inheritance, which is precisely what you're trying to express. You want T to be Address, Email an Phone at the same time (I assume those are class names). Thus is impossible. What's event more, this whole method makes no sense. You'll either have to introduce a base interface for all three classes or use three overloads of an Add method.

    0 讨论(0)
  • 2020-12-17 10:12

    How about creating an interface or base class for those three types?

    But looking at your code, seems that you're not using generic well enough. The point of using generic is that you don't need to cast it into any particular type (in this case, you are).

    0 讨论(0)
  • 2020-12-17 10:12

    In that case, I wouldn't bother, as you are comparing types anyway. Use this:

    public void Add(object Obj)
    {
        if (Obj is Address)
            m_Address.Add(Obj as Address);
        else if (Obj is Email)
            m_Email.Add(Obj as Email);
        else if (Obj is Phone)
            m_Phone.Add(Obj as Phone);
        else
            return;
    }
    

    I don't think multiple clauses are supported. You could also have separate method overloads too.

    0 讨论(0)
  • 2020-12-17 10:16

    You don't get any real benefits from generics in this case. I would just create different Add methods for each parameter Type.

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