返回类型有限的 C# 泛型

标签 c# generics

在 C# 中,我想制作一些专门的泛型,这些泛型仅用于从另一个泛型返回特定类型。专用泛型的目的是强制仅返回一些精确类型(如 double、double[]、byte、byte[])。也许最好的办法是通过一个例子来解释

var x = new MyGeneric<MyInterfaceDouble>();
double returnVal = x.getVal();

var x = new MyGeneric<MyInterfaceMyClass>();
MyClass returnVal = x.getVal();

所以我尝试了多种方法来实现这一目标,但无法做到这一点。最新迭代是:

public interface IMyInterface
{}

public interface IMyInterface<T, U> :IMyInterface
{
    U getValue();
}

public class MyInterfaceDouble: IMyInterface<MyInterfaceDouble, double>, IMyInterface
{
    public double getValue()
    {
        return 8.355; 
    }
}

public class MyGeneric<T> where T : IMyInterface
{}

但是我无法访问获取值

var x = new MyGeneric<MyInterfaceDouble>();
double returnVal = x.getVal();   // not available

这是怎么做到的?

最佳答案

看来您的设计将发生一些变化。

getVal 没有任何定义里面IMyInterface ,所以自然不可用于MyGeneric<MyInterfaceDouble> .

您将从 IMyInterface<T, U> 继承而不是IMyInterface :

public class MyGeneric<T> where T : IMyInterface<T, SomeSpecialType>
{}

更改IMyInterface定义有getVal与一般情况一样,返回 object :

public interface IMyInterface
{
    object getValue();
}

更改MyGeneric<T>对此的定义:

public interface IMyInterface
{ }

public interface IMyInterface<T>
{
    T getVal();
}

public class MyInterfaceDouble : IMyInterface<double>, IMyInterface
{
    public double getVal()
    {
        return 8.355;
    }
}

public class MyGeneric<T> where T : IMyInterface
{
    T Obj { get; }
}

并像这样使用:

var x = new MyGeneric<MyInterfaceDouble>();
double returnVal = x.Obj.getVal();   // available

还有一些其他解决方案,具体取决于您想要设计的愿景。

关于返回类型有限的 C# 泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45973627/

相关文章:

c# - UWP # 不显示 ListView.ItemTemplate 因为我从 List 更改为 ObservableCollection 和异步

c# - 求职面试测试

c# - 使用 LINQ 从使用 C# 的 HTML 中提取所有隐藏的输入

Java泛型类型的泛型类型

c# - 知道 TPL 数据流 block 是否繁忙的方法?

c# - 将部分类与普通类相结合

ios - ViewController 可以是包含 IBOutlets 等的通用吗?

c# - 通用 TryParse

java - Java 中的通用单例

c# - 如何链接接受 Func<> 委托(delegate)的方法重载? (C#)