Casting an object to two interfaces at the same time, to call a generic method

前端 未结 7 1734
我寻月下人不归
我寻月下人不归 2020-12-09 18:27

I want to call a generic method that constrains the input type T to implement two interfaces:

interface IA { }
interface IB { }
void foo(T t) where          


        
相关标签:
7条回答
  • 2020-12-09 19:20

    I don't believe what you want is possible if there is no type or interface which is applicable to all objects that you might want to accept. If you have control over the types of things that you'll be handling, you should define an interface which "inherits" all your constraints, and then have the function accept a parameter of that type. If you also want to include a base type in your constraint, define an interface:

    Interface ISelf(Of Out T)
      Function Self As T
    End Interface
    
    and then have the composite constraint interface inherit ISelf(Of DesiredBaseType). For example, if you are going to have a routine accept objects which derive from type Customer and implement both IDisposable and IEnumerable(Of String) [silly arbitrary example], define:

    Interface IDisposableEnumerableOfStringAndSelf(Of T)
      Inherits IDisposable, IEnumerable(Of String), ISelf(Of T)
    End Interface
    

    and then have those routines accept an IDIsposableEnumerableOfStringAndSelf(Of Customer).

    Note that this will only work if the class being passed in explicitly implements either IDIsposableEnumerableOfStringAndSelf(Of Customer) or else IDIsposableEnumerableOfStringAndSelf(Of T) for some T that's a subtype of Customer. Interfaces are not duck-typed (a fact which is important, since it's possible and sometimes useful to have an interface with no members, e.g. to indicate that a class promises to be immutable).

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