在C#中,我想制作一些专门的泛型,仅用于返回特定类型的形式,而不是泛型。专用泛型的目的是强制只返回一些确切的类型(比如double,double [],byte,byte [])。可能最好的解释通过一个例子C#泛型有限的返回类型
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
{}
但我不能访问GET值
var x = new MyGeneric<MyInterfaceDouble>();
double returnVal = x.getVal(); // not available
这又如何进行?
方法不可行你是什么意思,它不存在?还是关于保护级别?,在您的类定义中,您的方法名为:getValue,并调用getVal。不存在 – Ferus7
@ Ferus7我相信原因是MyGeneric不继承IMyInterface通用,所以它没有成员。我也尝试通过继承非通用IMyInterfece,但因为它没有成员也将不可用。 –
codiac
'MyGeneric'不会继承'T',也不会实现任何方法,所以不,您不会在该对象上找到'getVal'或'getValue'。请澄清你想在这里完成,因为语言不支持你在这里要求的。 –