开发者

c#: Method expects type

开发者 https://www.devze.com 2023-03-09 15:41 出处:网络
class Country { //props } dataContext is a variable with a method Set(), which works fine like as below dataContext.Set<Country>().SomeThing();
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

精彩评论

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