c# – 生成的LINQ类的动态属性访问
发布时间:2020-12-16 01:29:36 所属栏目:百科 来源:网络整理
导读:如何从生成的LINQ类中访问动态属性? 因为我希望能够自定义显示的表列 其中Partner是从SQL Server数据库表生成的LINQ类. table class="grid" thead tr % foreach (Column c in (IEnumerable)ViewData["columns"]) { % th%= c.Title %/th % } % /tr /thead tb
如何从生成的LINQ类中访问动态属性?
因为我希望能够自定义显示的表列 <table class="grid"> <thead> <tr> <% foreach (Column c in (IEnumerable)ViewData["columns"]) { %> <th><%= c.Title %></th> <% } %> </tr> </thead> <tbody> <% foreach (Partner p in (IEnumerable)ViewData.Model) { %> <tr> <% foreach (Column c in (IEnumerable)ViewData["columns"]) { %> ????? <th> <%= p.GetProperty(c.Name) %> </th> ????? <% } %> </tr> <% } %> </tbody> </table> 知道p.GetProperty(c.Name)方法的代码怎么样? 如果问题非常简单,请原谅我,因为我是C#和LINQ的新手 解决方法
反射在这里非常合适,但实际上 – 编译时都知道一切.因此可以在设计时指定所有内容.
public class DataItem { string Title {get;set;} object Value {get;set;} } public interface IDataItems { IEnumerable<DataItem> Items() } //suppose LINQ gives you this: public partial class Customer { public string Name {get;set;} public string Address {get;set;} public int Age {get;set;} } //then you add this in another file. //if there's a lot of this,it can be code genned by design-time reflection public partial class Customer : IDataItems { public IEnumerable<DataItem> IDataItems.Items() { yield return new DataItem() {"Name",Name}; yield return new DataItem() {"Address",Address}; yield return new DataItem() {"Age",Age}; } } //and the foreach loops look like this: foreach(DataItem d in ViewData.OfType<IDataItems>().First().Items()) { d.Title; } foreach(IDataItems container in ViewData.OfType<IDataItems>()) { foreach(DataItem d in container.Items()) { d.Value; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |