简体   繁体   中英

How to call generic overloaded method in C#

Not very familiar with C# and generics so I may be missing something obvious, but:

Given:

public interface IA { }

public interface IB
{  void DoIt( IA x );
}

public class Foo<T> : IB where T : IA
{
    public void DoIt( IA x )
    {  DoIt(x); // Want to call DoIt( T y ) here
    }

    void DoIt( T y )
    {  // Implementation
    }
}

1) Why doesn't the method void DoIt(T y) satisfy the DoIt method implementation required by interface IB ?

2) How can I call DoIt(T y) from within DoIt( IA x ) ?

1) Because any T is IA (this is given from contraint), but not every IA is T :

class A : IA {}
class B : IA {}

var foo_b = new Foo<B>();
var a = new A();

// from the point of IB.DoIt(IA), this is legal;
// from the point of Foo<B>.DoIt(B y), passed argument is not B
foo_b.DoIt(a);

2) If you are sure, that x is T , then use cast:

public void DoIt( IA x )
{  
    DoIt((T)x);
}

if x can be anything, and DoIt(T) can be optional, use as :

public void DoIt( IA x )
{  
    DoIt(x as T);
}

void DoIt( T y )
{
    if (y == null)
        return;

    // do it
}

Otherwise you can throw exception or consider another approach, depending on particular use case.

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