具有约束的通用类符合界面抱怨

时间:2016-04-28 08:46:20

标签: c# generics

为什么这不起作用?它抱怨Generic<T>没有实现接口成员'NormalInt.bsPro(LPP)'。 我也试过明确地实现了界面,但仍然没有运气!

class SomeType { }

interface NormalInt
{
    void bsPro(SomeType body);
}

class Generic<T>: NormalInt
    where T : SomeType
{

    public void bsPro(T body)
    {

    }
}

1 个答案:

答案 0 :(得分:2)

您需要从界面实现此方法。

public void bsPro(SomeType body)

特别期望参数中的SomeType实例。

编辑:

您需要使接口通用,然后约束imlpementing类,例如

public class SomeType
{
    public void Hello()
    {
        Console.WriteLine("Hello");
    }
}

public interface NormalInt<T>
{
    void bsPro(T body);
}

public class Generic<T> : NormalInt<T>
    where T : SomeType
{
    public void bsPro(T body)
    {
        body.Hello();
    }
}

public class Program
{
    private static void Main(string[] args)
    {
        var g = new Generic<SomeType>();
        var s = new SomeType();

        g.bsPro(s);
    }
}

我相信上述内容对您有用。