c# - 通用方法参数的接口(interface)约束

标签 c# generics

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

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();
    }
}

编辑

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

最佳答案

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

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;
    }
}

Test1会返回arg1的具体类型,而Test2只会返回接口(interface)。这通常用于流畅的界面。


扩展示例:

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

关于c# - 通用方法参数的接口(interface)约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10153826/

相关文章:

java - 是否可以检测不兼容类型与 Java 类型系统的比较?

c# - 在 Esc 键上关闭 Ajax Modal 弹出窗口

c# - EF 扩展每个案例的查询

c# - 在 javascript 操作后获取 HtmlDocument

c# - 自定义 URL 中带有 + 号的参数

java - 使用泛型类型进行 Spring 依赖注入(inject)

c# - RijndaelManaged - 设置 KeySize 属性有什么作用?

java - 针对泛型和特定类型或该类型列表的灵活 JAXB XML 解析

java - 如何在java中实现我自己的通用集合?

Java 泛型和专门的构造函数