use*_*535 16 c# generics reflection
我有一个泛型类,其中我有一个函数来获取传递的泛型对象的属性.它如下所示.
public class ExportToCsv<T>
where T: class
{
public ExportToCsv(List<T> obj)
{
this.Data = obj;
}
public StringBuilder CreateRows()
{
IEnumerable<PropertyInfo> properties = typeof(T).GetProperties();
}
}
Run Code Online (Sandbox Code Playgroud)
如果我通过从下面的对象(类)中选择来传递对象,它工作正常并返回属性
//GetLeadingRoutingRecords returns a class/object
var result = from obj in GetLeadRoutingRecords()
select new
{
LeadRoutingId = obj.LeadRoutingID,
Make = obj.Make
};
Run Code Online (Sandbox Code Playgroud)
并将结果传递给 result.ToList();
但是当我尝试通过为下面的属性创建一个类来创建我自己的匿名对象时,它无法返回任何属性
注意:下面的代码是在循环中调用的,它运行良好并传递给上面的函数可以通过调试查看所有值.
public CsvReport function return(){
return new CsvReport
{
ShopName = this.val,
TargetVehicleName = val
}.ToList();
}
Run Code Online (Sandbox Code Playgroud)
我为上面的匿名对象编写的类如下所示:
public class CsvReport
{
public string ShopName { get; set; }
public string TargetVehicleName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
所以在这种情况下它不起作用,我选择第一个记录并获得如下属性
this.Data.First().GetType().GetProperties();
Run Code Online (Sandbox Code Playgroud)
我想在这里使用第一个模式,也就是说 type(T).GetProperties
所以,任何工作请........................
Mar*_*ell 31
对typeof(T)工作的反思; 这是一个基于你的简单例子,但(重要的是)可以运行.它输出:
ShopName
TargetVehicleName
Run Code Online (Sandbox Code Playgroud)
码:
using System;
using System.Collections.Generic;
public class CsvReport
{
public string ShopName { get; set; }
public string TargetVehicleName { get; set; }
}
class ExportToCsv<T>
{
List<T> data;
public ExportToCsv(List<T> obj)
{
data = obj;
}
public void WritePropNames()
{
foreach (var prop in typeof(T).GetProperties())
{
Console.WriteLine(prop.Name);
}
}
}
static class Program
{
static void Main()
{
var obj = new List<CsvReport>();
obj.Add(new CsvReport { ShopName = "Foo", TargetVehicleName = "Bar" });
new ExportToCsv<CsvReport>(obj).WritePropNames();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21397 次 |
| 最近记录: |