开发者

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:

  1. Find the MethodInfo object for your set method.
  2. MakeGenericType on that MethodInfo with the o.GetType().
  3. 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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜