在我寻求正确理解 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/