如何将方法组转换为等效的类

如何将方法组转换为等效的类

本文介绍了如何将方法组转换为等效的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



首先我很抱歉英语不好,因为我不是本地人,但非常喜欢C#和初学者。

firstly I'm sorry for bad English because I'm not native but very intersted in C# and beginner to it.

我有一个sql表,它也是一个类,在实体模型中称为CreditCard,以及一个方法组:

I have a sql table that it is a class also, called CreditCard in entity model, and a method group:

db.Gettype().GetProperty("CreditCard").GetValue(db,null)

db是AdventureWorks2012Entities的实例,即

db is instance of AdventureWorks2012Entities i.e

AdventureWorks2012Entities db = new AdventureWorks2012Entities();

该方法组相当于CreditCard类,即如果编译该方法组,则在保持鼠标指针时获得相同的结果在它上面(metod组),当你将CreditCard上的鼠标指针作为一个类时,结果相同。

that method group is equivalent of CreditCard class i.e if you compile that method group you get the same results when you hold mouse pointer on it (metod group) and the same results when you hold mouse pointer on CreditCard as a class.

现在我想使用这段代码:

Now I want to use this code:

datagrid.itemsource=db.CreditCard.ToList();

但我在这段代码中没有使用CreditCard,我想使用CreditCard类,即我想使用代码类似这样的事情:

but I do not use of CreditCard in this code and I want to use of CreditCard class i.e I want to use the code something like this:

datagrid.itemsource=db.*(db.Gettype().GetProperty("CreditCard").GetValue(db,null))*.ToList();

但是我从代码中得到[... db。(db ...]的一部分错误:标识符预期;

but I get an error with part of [...db.(db...] from the code as : Identifier expected;

我想我不能使用 db.Gettype()。GetProperty(" CreditCard")。GetValue(db,null)而不是
CreditCard 。(datagrid.itemsource = ......)

I think I can't usedb.Gettype().GetProperty("CreditCard").GetValue(db,null) instead ofCreditCard in that code.(datagrid.itemsource=......)

我该怎么办?问候。

推荐答案

如果我了解你想要在运行时动态更改datagrid ItemSource属性,可以试试这段代码: 

If I understand you want to dynamically change your datagrid ItemSource property at runtime, can you try this code snippet : 

// the DbContext type has a method generic method 'Set<T>()' // when using this method all you have is to specify the type // parameter T in your case T is Credit Card :

dataGrid.ItemSource = db.Set<CreditCard>().ToList();

// othrwise if you you want to know how to do it using reflection,
// here is an example

var creditCardSet = (IQueryable<CreditCard>)db.GetType().GetProperty("CreditCard").GetValue(db);
var sourceList = creditCardSet.ToList();


// if you want a method to bind the datagrid based on the type :

public void BindDataGrid<T>(ref DataGrid grid)
   where T: class
{
   grid.ItemSource = db.Set<T>().ToList();
}

希望它有所帮助;

良好的编码;


这篇关于如何将方法组转换为等效的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:45