2017-08-31 109 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