我想传递一个类作为参数。
所以我想做的是传递一个类,例如:“Customer”到一个方法。 我想这样做是因为这样我也可以将例如“Contract”作为类传递给相同的方法。这样我就不需要为每个类都创建一个方法。
附带信息:我正在使用 EntityFramework 6、MVC 5、Nest 1.0 和 ElasticSearch 1.4
这个概念是我们将东西放在 ElasticSearch 中,然后我们可以进行搜索。 搜索查询是:
SearchElasticClient.Search<Customer>(body => body
.AllIndices()
.Size(500)
.Query(query => query
.Bool(@bool => @bool
.Must(must => must
.QueryString(qs => qs
.Query("XXXX"))))));
对于契约(Contract):
SearchElasticClient.Search<Contract>(body => body
.AllIndices()
.Size(500)
.Query(query => query
.Bool(@bool => @bool
.Must(must => must
.QueryString(qs => qs
.Query("XXXX"))))));
如您所见,如果我想搜索我们拥有的每种类型,那么我需要至少复制粘贴此查询 20 次。
我不喜欢复制粘贴,因为代码不合适,当我需要更改它时,工作量会很大。
所以我想创建一个方法,将我的类作为参数或类似的东西,这样我就可以创建一个通用方法来重用这个代码块。
所以对于我们的例子:
我的( Entity Framework )类:
public class Customer{
public int CustomerID {get;set;}
public String CustomerName {get;set;}
}
public class Contract{
public int ContractID {get;set;}
public String ContractName {get;set;}
}
类之间的关系对我来说无关紧要,所以我将它们排除在外。
然后在我的 HomeController 中我想要类似的东西
public class HomeController : Controller
{
...
public ActionResult Search(String textToSearch)
{
//So here you see that I want to use the same method for both classes.
Customer customer = Helpers.SearchHelper.Search(textToSearch);
Contract contract = Helpers.SearchHelper.Search(textToSearch);
}
}
然后我的 SearchHelper 会是这样的:
public static class SearchHelper
{
public static ElasticClient SearchElasticClient
{
get
{
Uri uri = new Uri("http://localhost:9200");
var setting = new ConnectionSettings(uri, "default_INDEX");
return new ElasticClient(setting);
}
}
public static void SearchTest(String textToSearch, MyClass)
{
var test = SearchElasticClient
.Search<Customer>(body => body
.AllIndices()
.Size(500)
.Query(query => query
.Bool(@bool => @bool
.Must(must => must
.QueryString(qs => qs
.Query("XXXX"))))));
}
}
如您所见,现在我将我的类“Customer”固定在我的代码中。 我想用变量或其他东西替换它。
现在我尝试了什么:
public static void SearchTest<T>(String textToSearch)
{
var test = SearchElasticClient
.Search<T>(body => body
.AllIndices()
.Size(500)
.Query(query => query
.Bool(@bool => @bool
.Must(must => must
.QueryString(qs => qs
.Query("XXXX"))))));
}
在这里我得到编译错误:“无法将 lambda 表达式转换为类型‘Nest.ISearchRequest’,因为它不是委托(delegate)类型。”
我不熟悉委托(delegate)及其工作原理以及是否可以使用它,因此如果我需要委托(delegate),请提供足够的详细信息。
我也试过:
public static void SearchTest(String textToSearch, Type myClass)
{
var test = SearchElasticClient
.Search<myClass>(body => body
.AllIndices()
.Size(500)
.Query(query => query
.Bool(@bool => @bool
.Must(must => must
.QueryString(qs => qs
.Query("XXXX"))))));
}
然后它给我编译错误:“找不到类型或命名空间‘myClass’。”我明白为什么会收到此错误,所以我知道它更像是 public static void Search(..){..} 但我不知道如何实现它。
我希望这是对我的问题的更好解释。
所以它是“嵌套”搜索的一个实现,我想避免复制粘贴搜索查询。
提前致谢
最佳答案
我相信你想要做的是使 Search
通用
public static classToPass Search<classToPass>()
然后像这样使用它
Test x = Helper.Search<Test>(); //Test = class as definied above
TestTwo y = Helper.Search<TestTwo>();
关于c# 将类作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28458012/