问题
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:
instance.GetType(): this method (defined in Object) will return the instance's type.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