c#:方法需要类型

Pra*_*sad 1 c#

class Country
{
   //props
}
Run Code Online (Sandbox Code Playgroud)

dataContext是一个带有方法Set()的变量,它的工作方式如下所示

dataContext.Set<Country>().SomeThing(); 
Run Code Online (Sandbox Code Playgroud)

但我不想硬编码类型=国家,而是我想从变量中提取类型,例如

function MyFunction(object o)
{
   dataContext.Set</*something_here*/>().SomeThing();
   //some how extract type from variable o
}
Run Code Online (Sandbox Code Playgroud)

Nik*_*Nik 10

怎么样:

void MyFunction<T> (T o)
{
    dataContext.Set<T> ().SomeThing ();
}
Run Code Online (Sandbox Code Playgroud)

然后用:

MyFunction<County> (county_object);
Run Code Online (Sandbox Code Playgroud)

  • 这可以缩短为`MyFunction(country_object);`. (2认同)