反射在c#中没有获得自定义类

本文关键字:自定义 反射 | 更新日期: 2023-09-27 18:14:16

我创建了一个从任何类返回默认字段值的方法。我正试图使用Reflection来获取值,但它不起作用。

下面是我想要的默认值(StoredProcedure)的类:

namespace Services.Data.Report
{
  public class PayrollReport
  {
    public string FullName { get; set; }
    public DateTime WeekStart { get; set; }
    public decimal PerDiem { get; set; }
    public decimal StPay { get; set; }
    public decimal OtPay { get; set; }
    public decimal StraightHours { get; set; }
    public decimal OverTimeHours { get; set; }
    [DefaultValue("report_payrollSummary")]
    public string StoredProcedure { get; set; }
  }
}

我有这个方法,将允许我传递类的名称,并希望得到所需的字段值:

namespace Services
{
  public class DynamicReportService : IDynamicReportService
  {     
    public string GetDynamicReport(string className)
    {
        System.Reflection.Assembly assem = typeof(DynamicReportService).Assembly;
        var t = assem.GetType(className);
        var storedProcedure = t?.GetField("StoredProcedure").ToString();
        return storedProcedure;
    }
  }
}

我也试过这个,但得到相同的结果:

var t = Type.GetType(className);

问题是t从未设置。

我试着用这样的方式来调用它:

var storedProc = _dynamicReportService.GetDynamicReport("Services.Data.Report.PayrollReport");

是否有另一种方法通过名称传递Class并能够访问字段、方法和其他属性?

反射在c#中没有获得自定义类

试试这个:

System.Reflection.Assembly assembly = typeof(DynamicReportService).Assembly;
var type = assembly.GetType(className);
var storedProcedurePropertyInfo = type.GetProperty("StoredProcedure"); 
var defaultValueAttribute = storedProcedurePropertyInfo.GetCustomAttribute<DefaultValueA‌​ttribute>();
return defaultValueAttribute.Value.ToString();

首先我们将从类型中获得StoredProcedure PropertyInfo,然后我们将使用GetCustomAttribute<T>扩展查找属性DeafultValueAttribute,最后我们将获取属性值并返回它。