泛型使用where限制基类

时间:2012-03-11 19:42:11

标签: c# generics

我有一个方法:

private double FindPrice<T>(T l_Price_Breaks) where T : ?
{
}

?我想限制为3个类X,Y,Z。这三个类来自一个名为child的类:

public class X : Child
public class Y : Child
public class Z : Child

我不能这样做:

private double FindPrice<T>(T l_Price_Breaks) where T : Child  
{
}

它有效但当我尝试使用以下方法调用此方法时:

X MyX = new X();
double return = FindPrice(MyX);

我得到“没有从X到Child的隐式转换”。

3 个答案:

答案 0 :(得分:1)

你可以,但你的代码还有另外一堆问题,比如

  

预期的标识符; 'return'是关键字。

Public需要public等。

如果您像这样重写代码

class GenericTest
{
    public class Child { }
    public class X : Child { }
    public class Y : Child { }
    public class Z : Child { }


    private double FindPrice<T>(T l_Price_Breaks) where T : Child
    {
        return 2;
    }

    private void foobar()
    {
        X MyX = new X();
        double retValue = FindPrice(MyX);
    }
}

它汇编得很好。

答案 1 :(得分:1)

代码对我有用,只有一个例外:你有一个名为return的变量名,它不起作用,因为这是c#中的保留关键字。将其重命名为result

答案 2 :(得分:0)

您遗漏了一些基本信息,例如FindPrice的实施,但我猜测您在Child中使用T代替FindPrice {1}}方法。