2017-08-31 106 views
2

在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 

這又如何進行?

+0

方法不可行你是什麼意思,它不存在?還是關於保護級別?,在您的類定義中,您的方法名爲:getValue,並調用getVal。不存在 – Ferus7

+0

@ Ferus7我相信原因是MyGeneric 不繼承IMyInterface通用,所以它沒有成員。我也嘗試通過繼承非通用IMyInterfece,但因爲它沒有成員也將不可用。 – codiac

+0

'MyGeneric '不會繼承'T',也不會實現任何方法,所以不,您不會在該對象上找到'getVal'或'getValue'。請澄清你想在這裏完成,因爲語言不支持你在這裏要求的。 –

回答

2

看來你會對你的設計有所改變。

getVal沒有任何關於IMyInterface的內容,因此MyGeneric<MyInterfaceDouble>自然不適用。

你會從IMyInterface<T, U>而不是IMyInterface繼承:

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

OR

變化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 

此外還有一些其他的解決方案,這取決於你想設計自己的眼光。

+0

如果MyGeneric將繼承IMyInterface 將不會執行。第二個版本:之後將返回對象。 – codiac

+0

第三個版本非常接近。這幾乎是完美的。這也簡化了專門的泛型和界面 – codiac