c# - 从仅在方法中设置类型的接口(interface)获取具有泛型类型的对象

标签 c# inheritance

这不起作用:

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/

相关文章:

c# - 径向 TreeMap 布局 : fix beizer curves

c# - 根据用户输入以编程方式创建 Hangfire cron 表达式

c# - 用一条 LINQtoSQL 语句返回不同的对象

C++ 用抽象类重载输入

C++ 继承和确定类型

c# - 通过代码,我如何测试硬盘驱动器是否正在 sleep 而不唤醒它

c# - 如何通过 SSL 从 LDAP 获取 DirectoryEntry?

Java:如何访问类层次结构中某个成员更改其数据类型的对象的成员

java - Java中继承的静态方法中获取类名

c++ - 为什么我会得到带有 protected 静态成员的 C2248(无法访问的成员)?