简体   繁体   English

对象参数和通用参数(类型参数)之间的差异

[英]difference between object parameter and generic parameter(type parameter)

I was thinking about the difference between object parameter and generic parameter? 我在考虑对象参数和通用参数之间的区别吗?

public foo<T>(T abc)

public foo(object abc)

Actual both are kind of variable and I could convert many Object into anything I like to, because its the base class everything 实际上两者都是变量,我可以将许多Object转换成我喜欢的任何东西,因为它是所有的基类

Whatare te difeerences? 什么是差异?

Generics are complex topic and I would suggest you to dive deeper if you don't understand the difference. 泛型是一个复杂的话题,如果您不了解其中的区别,我建议您更深入地研究。

In short: by using object you exposes yourself to run-time exceptions when you expect object to be of type A but in fact it is of type B. Generics are there to provide type safety by removing the duty of creating many eg functions doing the same thing for many different types. 简而言之:通过使用对象,当您期望对象为A类型但实际上为B类型时,您将自己暴露于运行时异常。泛型通过消除创建许多函数(例如执行许多不同类型的事物都是相同的。 By using genetric constraints you can create powerful and safe solutions. 通过使用通用约束,您可以创建功能强大且安全的解决方案。

Further reading: 进一步阅读:

https://msdn.microsoft.com/library/d5x73970.aspx?f=255&MSPPError=-2147217396 https://msdn.microsoft.com/en-us/library/512aeb7t.aspx https://msdn.microsoft.com/library/d5x73970.aspx?f=255&MSPPError=-2147217396 https://msdn.microsoft.com/en-us/library/512aeb7t.aspx

performance - when converting value type to object, boxing and unboxing are very expensive. 性能-将值类型转换为对象时,装箱和拆箱非常昂贵。 type safe - need to cast objects, you lose compile-time type safety. 类型安全-需要转换对象,您将失去编译时类型安全。

generics solve this issues. 泛型解决了这个问题。

it's hard to tell difference without seeing your methods . 不看自己的方法就很难分辨差异。 If your methods are just writing the type of inputs to console, there is no difference. 如果您的方法只是将输入类型写入控制台,则没有区别。 But if your methods are casting object and doing something there are differences. 但是,如果您的方法强制转换对象并执行某些操作,则存在差异。

Generics are very powerful because of constraints and they can inherit from other generics type. 由于约束,泛型非常强大,并且它们可以从其他泛型类型继承。

So General Difference: 所以一般区别:

Type Safety: you can send anything, but while casting you can get error at runtime with objects. 类型安全:您可以发送任何内容,但是在投射时,对象运行时会出错。 if you use constraints you will get error at compile time with generics. 如果使用约束,则在泛型编译时会出错。

Cleaner Code: you will always use casting with object. 清洁代码:您将始终对对象使用强制转换。 You don't have to do this with generics. 您不必使用泛型。

Better Performance (For Value Types): there will be no boxing and unboxing with generics. 更好的性能 (对于值类型):不会对泛型进行装箱和拆箱。 if you send value type, it will first put this memory heap (boxing) then it will get to thread stack from memory heap (unboxing) with object. 如果发送值类型,它将首先将该内存堆(装箱)放入,然后与对象一起从内存堆(拆箱)进入线程堆栈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM