C# 具有符合接口投诉的约束的泛型类

C# 具有符合接口投诉的约束的泛型类,c#,generics,C#,Generics,为什么这样不行?它抱怨Generic没有实现接口成员“NormalInt.bsPro(LPP)”。 我也尝试过显式地实现接口,但仍然没有成功 class SomeType { } interface NormalInt { void bsPro(SomeType body); } class Generic<T>: NormalInt where T : SomeType { public void bsPro(T body) { }

为什么这样不行?它抱怨
Generic
没有实现接口成员“NormalInt.bsPro(LPP)”。 我也尝试过显式地实现接口,但仍然没有成功

class SomeType { }

interface NormalInt
{
    void bsPro(SomeType body);
}

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

    public void bsPro(T body)
    {

    }
}
class SomeType{}
接口法线
{
void bsPro(SomeType body);
}
类泛型:NormalInt
T:什么类型
{
公共空间bsPro(T体)
{
}
}

您需要从接口实现此方法

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);
    }
}
公共类SomeType
{
公共空间
{
Console.WriteLine(“你好”);
}
}
公共接口规范
{
空心bsPro(T体);
}
公共类泛型:NormalInt
T:什么类型
{
公共空间bsPro(T体)
{
body.Hello();
}
}
公共课程
{
私有静态void Main(字符串[]args)
{
var g=新的泛型();
var s=新的SomeType();
g、 bsPro(s);
}
}

我相信上面的方法应该适合您。

您需要从接口实现此方法

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);
    }
}
公共类SomeType
{
公共空间
{
Console.WriteLine(“你好”);
}
}
公共接口规范
{
空心bsPro(T体);
}
公共类泛型:NormalInt
T:什么类型
{
公共空间bsPro(T体)
{
body.Hello();
}
}
公共课程
{
私有静态void Main(字符串[]args)
{
var g=新的泛型();
var s=新的SomeType();
g、 bsPro(s);
}
}

我相信以上这些应该对你有用。

是的,但是T是某种类型的……不管发生了什么,o_O@schwarz这不是多态性,这是变异性
Dog
是(带有
Animal
的变形)的一个子类型,但
List
不是
List
@schwarz的一个子类型-这不安全,因为您可以执行
NormalInt i=new Generic();i、 bsPro(new SomeType())
,这将允许您将
SomeType
传递给需要
sometsubtype
@Lee的方法,这正是我所寻找的。谢谢…不知怎的,我错过了:是的,但是T是某种类型的…不管发生了什么_O@schwarz这不是多态性,这是变异性
Dog
是(带有
Animal
的变形)的一个子类型,但
List
不是
List
@schwarz的一个子类型-这不安全,因为您可以执行
NormalInt i=new Generic();i、 bsPro(new SomeType())
,这将允许您将
SomeType
传递给需要
sometsubtype
@Lee的方法,这正是我所寻找的。谢谢……不知怎的,我错过了:P