2016-03-10 22 views
2

不是很熟悉C#和泛型泛型重載的方法,所以我可能失去了一些東西很明顯,但:如何調用C#

考慮:

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)爲什麼沒有方法void DoIt(T y)滿足接口IB要求的DoIt方法實現?

2)如何從DoIt(IA x)內撥打DoIt(T y)

+1

對我來說嗯我沒有看到有理由限制T這樣做,因爲IB的'DoIt'實現實際上只接受'IA'作爲參數,所以爲什麼要再限制一次呢?就我的觀點而言,這只是一種無用的層面。 – ckruczek

+0

@ckruczek:當'Foo '的後代必須執行一些'T'特定操作時,這可能很有用,並且它們全部應該存儲在同一個容器(例如,集合)中。 – Dennis

回答

3

1)因爲任何TIA(這是從contraint給出),但不是每個IAT

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)如果您是肯定的,那xT,然後使用演員表:

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

if if x can be anythi NG,並DoIt(T)可任選,使用as

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

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

    // do it 
} 

否則,您可以拋出異常,或者考慮另一種方法,這取決於具體的使用情況。