在 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/