2012-10-04 42 views
2

這不起作用:獲取與接口泛型類型對象只設置方法的類型

public interface IServerFuncs 
{ 
    Table<T> getTable<T>() where T : MasterClass; 
    //*cut* other stuff here 
} 

public class DefaultFuncs<T> : IServerFuncs where T : MasterClass 
{ 
    Table<T> table; 

    public DefaultFuncs(Table<T> table) 
    { 
     this.table = table; 
    } 

    public Table<T> getTable() 
    { 
     return table; 
    } 
} 

它最高審計機關DefaultFuncs<T>' does not implement interface member 'IServerFuncs.getTable<T>()'

但我不能做到這一點無論:

public Table<T> getTable<T>() where T:MasterClass 
{ 
    return table; 
} 

現在是Error: Cannot implicitly convert type 'MySQLCache.Table<T>。我猜噸與DefaultFuncs<T>方法的衝突,所以我嘗試:

public Table<T2> getTable<T2>() where T2:MasterClass 
{ 
    return table; 
} 

但它給出了另一個錯誤:Error Cannot implicitly convert type 'Table<T>' to 'Table<T2>'

我需要得到這個無需添加泛型類型,以IServerFuncsIServerFuncs<T>)工作..有任何想法嗎?

+0

基礎'getTable()'不應該是通用的。另外,公共成員名稱應該是UpperCamelCase。 – SLaks

+2

由於'getTable'允許客戶端選擇'T'類型,即使只有一種可能的類型,也沒有一種解決方法。如果你不能使'IServerFuncs'成爲通用的,那麼你唯一的選擇是拋出一個異常,如果'T2!= T'或者添加一個非通用接口到'表'並返回。 – Lee

回答

1

你可以做

public Table<T2> getTable<T2>() where T2:MasterClass 
{ 
    return (Table<T2>)(object)table; 
} 

如果你知道T和T2將永遠是相同的類型。如果他們不是,你會得到一個運行時異常。

+0

我會看看我是否可以解決這個問題,因爲它很混亂,但它的確有用。謝謝;) – natli

+0

爲什麼不在這裏說'where T2:T'?但無論如何,這很醜陋。 「IServerFuncs」通用似乎很自然(所以'IServerFuncs '),因爲你真的不希望你的**方法**是通用的。你爲什麼不喜歡'IServerFuncs '? –

1

我不認爲你可以做到這一點無需添加模板修改的界面,否則,你可以這樣做:

public class MC1 : MasterClass 
{ 
} 

public class MC2 : MasterClass 
{ 
} 

IServerFuncs df = new DefaultFuncs<MC1>(new Table<MC1>()); 
Table<MC2> table = df.getTable<MC2>(); // obviously not correct. 

基本上,以保證同類型使用的界面和實現,需要在預選賽添加到接口定義:

public interface IServerFuncs<T> where T : MasterClass 
{ 
    Table<T> getTable(); 
    //*cut* other stuff here 
} 

public class DefaultFuncs<T> : IServerFuncs<T> where T : MasterClass 
{ 
    Table<T> table; 

    public DefaultFuncs(Table<T> table) 
    { 
     this.table = table; 
    } 

    public Table<T> getTable() 
    { 
     return table; 
    } 
}