一般的参数差异限制在一个接口,只需使用接口 [英] Difference between generic argument constrained to an interface and just using the interface

查看:118
本文介绍了一般的参数差异限制在一个接口,只需使用接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是什么之间的区别:

 无效的MyMethod(IMyInterface的值)
{
    // ...
}
 

和这样的:

 无效的MyMethod< T>(吨价),其中T:IMyInterface的
{
    // ...
}
 

解决方案

主要功能不同的是,你可以知道对象的泛型方法里面的实际类型。 t参数将包含实际的类型,它可以在某些情况下是有利的。

在非一般的情况下,你不能保证获得对象的基本类型。大多数类型的,你可以抓住value.GetType(),但用户可以通过空和阻止你。

What is the difference between this:

void MyMethod(IMyInterface value)
{
    //...
}

and this:

void MyMethod<T>(T value) where T : IMyInterface
{
    //...
}

解决方案

The main functional difference is that you can know the actual type of the object inside of the generic method. The T parameter will contain the actual type which can advantageous in certain scenarios.

In the non-generic case you cannot guarantee access to the underlying type of the object. Most of the type you could grab value.GetType() but the user could pass Null and thwart you.

这篇关于一般的参数差异限制在一个接口,只需使用接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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