c#: Method expects type
class Country
{
//props
}
dataContext is a variable with a method Set(), which works fine like as below
dataContext.Set<Country>().SomeThing();
but i dont want to hard code the type=Country, rather i want to extract type out from a variable eg
function MyFunction(object o)
{
dataContext.Set</*something_here*/>().SomeThing();
//some how extract type from va开发者_如何学编程riable o
}
How about:
void MyFunction<T> (T o)
{
dataContext.Set<T> ().SomeThing ();
}
Then call it with:
MyFunction<County> (county_object);
In addition to the other answers, you can do this with some reflection trickery. Basically, it's going to boil down like so:
- Find the MethodInfo object for your set method.
MakeGenericType
on that MethodInfo with theo.GetType()
.- Invoke that method and then the
SomeThing
method.
Trying to code this from memory here, so please pardon any code errors:
var setMethod = dataContext.GetType().GetMethods().First(x => x.Name == "Set");
var genericVersion = setMethod.MakeGenericType(o.GetType());
var result = genericVersion.Invoke(dataContext, null) as WhateverSetReturns;
result.SomeThing();
精彩评论