在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'。請澄清你想在這裏完成,因爲語言不支持你在這裏要求的。 –