泛型方法参数的接口约束

17 c# generics

在我正确理解C#的过程中,我发现自己在询问在泛型方法参数上指定接口约束与简单地将接口指定为参数类型之间的实际区别是什么?

public interface IFoo
{
    void Bar();
}

public static class Class1
{
    public static void Test1<T> (T arg1) where T : IFoo
    {
        arg1.Bar();
    }

    public static void Test2(IFoo arg1)
    {
        arg1.Bar();
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

我知道我的例子非常狭窄,因为它只是一个例子.我对超出其范围的差异非常感兴趣.

Dan*_*rth 12

在您的具体示例中,没有区别.但采取以下方法:

public static class Class1
{
    public static T Test1<T>(T arg1) where T : IFoo
    {
        arg1.Bar();
        return arg1;
    }

    public static IFoo Test2(IFoo arg1)
    {
        arg1.Bar();
        return arg1;
    }
}
Run Code Online (Sandbox Code Playgroud)

Test1将返回特定类型的arg1,而Test2只返回接口.这通常用于流畅的界面.


扩展示例:

public interface IFoo
{
    void Bar();
}

public class Foo : IFoo
{
    // implementation of interface method
    public void Bar()
    {
    }

    // not contained in interface
    public void FooBar()
    {
    }
}


var foo = new Foo();
Class1.Test1(foo).FooBar(); // <- valid
Class1.Test2(foo).FooBar(); // <- invalid
Run Code Online (Sandbox Code Playgroud)


Teo*_*gul 6

您给出的示例没有一点差异.另一方面,使用通用版本使您能够where T : IFoo, IOther在将来扩展约束列表(),而无需更改方法签名.