How to pass an Object type to Type parameter in C#

£可爱£侵袭症+ 提交于 2019-12-05 07:30:47

The typeof keyword when you know the class at compile time.

SetValuesToObject(typeof(Product),datarow);

You can also use object.GetType() on instances that you don't know their type at compile time.

You have a few options:

  1. instance.GetType() : this method (defined in Object) will return the instance's type.
  2. typeof(MyClass) : will give you the type for a class.

Finally, if you own the method, you could change it to use Generics, and call it like this instead

SetValuesToObject<Product>(datarow)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!