这不起作用:
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>
。我猜方法中的 T 与 DefaultFuncs<T>
冲突所以我尝试了:
public Table<T2> getTable<T2>() where T2:MasterClass
{
return table;
}
但它又给出了另一个错误:Error Cannot implicitly convert type 'Table<T>' to 'Table<T2>'
我需要在不向 IServerFuncs
添加泛型类型的情况下使其正常工作(IServerFuncs<T>
)..有什么想法吗?
最佳答案
你可以做到
public Table<T2> getTable<T2>() where T2:MasterClass
{
return (Table<T2>)(object)table;
}
如果您知道 T 和 T2 始终是同一类型。如果不是,您将收到运行时异常。
关于c# - 从仅在方法中设置类型的接口(interface)获取具有泛型类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12735334/