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

江枫思渺然 提交于 2019-12-10 04:25:00

问题


I have a function that has Type Parameter.

public static object SetValuesToObject(Type tClass, DataRow dr)
{
   //
   .............
   //
   return object
} 

I have no idea how to pass a class as parameter for this function. Here i want to pass parmeter Class "Product".

I tried this

 SetValuesToObject(Product,datarow);

But it doesn't work. How could i do this?


回答1:


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.




回答2:


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)



来源:https://stackoverflow.com/questions/19673819/how-to-pass-an-object-type-to-type-parameter-in-c-sharp

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