有什么区别:
public void Method1<T>(class1 c, T obj) where T:Imyinterface
Run Code Online (Sandbox Code Playgroud)
和
public void Method2(class1 c, Imyinterface obj)
Run Code Online (Sandbox Code Playgroud)
?
使用第一种方法有什么好处?
虽然在您的场景中它实际上是相同的(除了使用接受接口参数的方法会将具体对象向上转换为接口类型这一事实),但请考虑稍微不同的场景。假设我们希望我们的方法只接受实现两个接口的类IMyInterface1,IMyInterface2否则代码不应编译:
interface IMyInterface1 { }
interface IMyInterface2 { }
class MyClass : IMyInterface1 { }
public void Method1<T>(Class1 c, T obj) where T : IMyInterface1, IMyInterface2
{
}
Run Code Online (Sandbox Code Playgroud)
如果我们创建接受接口作为第二个参数的方法,它将不满足条件,因为它不会限制用户发送仅实现一个接口但不实现第二个接口的类实例,就像本例中的 MyClass 和 IMyInterface2 一样例子。
用户应该发送什么接口?他并不真正知道需要在编译时发送的类型。
这是使用泛型和泛型约束的好地方,但另一方面我们不能使用单个接口参数。