接口参数或在那里泛型方法 - 的区别是什么? [英] interface as argument or generic method with where - what is the difference?

查看:127
本文介绍了接口参数或在那里泛型方法 - 的区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时之间的差异:IMyInterface的$:

Is any difference between :

public void Method1<T>(class1 c, T obj) where T:Imyinterface

public void Method2(class1 c, Imyinterface obj)

什么是使用第一种方法的好处是什么?

What are the benefits of use the first one method?

推荐答案

而在你的情况下它实际上同样的(除了一个事实,即与方法接受接口参数会上溯造型的具体对象接口类型)考虑方案稍有不同。比方说,我们希望我们的方法只接受实现两个接口类 IMyInterface1 IMyInterface2 键,否则代码不应该编译

While in your scenario it's practically the same (except the fact that with method accepting interface parameter it will upcast concrete object to interface type) consider slightly different scenario. Let's say we want our method to accept only class that implements two interfaces IMyInterface1 and IMyInterface2 and that otherwise code should not compile :

interface IMyInterface1 { }    

interface IMyInterface2 { }

class MyClass : IMyInterface1 { }

public void Method1<T>(Class1 c, T obj) where T : IMyInterface1, IMyInterface2
{

}

如果我们创建一个接受接口作为它的第二个参数,它不会满足的条件,因为它没有从限制用户的方法发送一个实现只有一个接口,但像它是用于MyClass的和IMyInterface2在这个例子不实现第二接口类实例。

If we create method that accepts interface as it's second parameter it will not satisfy the condition because it doesn't restrict user from sending class instance that implements only one interface but doesn't implements the second interface like it is for MyClass and IMyInterface2 in this example.

和用户应该送什么接口?他真的不知道,需要在编译时发送的类型。

And what interface should user send ? He don't really know the type that needs to send on compile-time.

这是一个好地方使用通用和通用约束,并在另一方面,我们不能用单一的接口参数。

This is a good spot to use generic and generic constrains and on the other hand we cannot use single interface parameter.

这篇关于接口参数或在那里泛型方法 - 的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆