2016-10-22 59 views
0

我創建了一個方法來從任何類中返回默認的字段值。我正在嘗試使用Reflection來獲得價值,但它不起作用。反射沒有得到C#中的自定義類

這裏是我想要的默認值(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的名字,並能夠訪問該字段,方法和其他屬性?

+2

您是否在className中傳遞了該類的完整程序集限定名?它應該是「namespace.classname,assemblyname」,因此「Services.Data.Report.PayrollReport,Services.Data.Report」假定名稱空間與程序集匹配。爲了檢查你可以在類中運行它並捕獲輸出:this.GetType()。AssemblyQualifiedName – jimpaine

+0

當你調用'GetDynamicReport'時,你期待什麼?在你的例子中,你是否期望得到值爲「report_payrollSummary」的字符串? – RVid

+0

如果你想獲得'Property'的'Attribute'的值,你將需要獲得屬性(它不是一個字段)並使用反射來獲取屬性。 'ToString()'不會給你。見例如http://stackoverflow.com/q/6637679/224370 –

回答

2

試試這個:

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並在結束時,我們將採取的屬性值,並將其返回。

+1

使用'var deafultValueAttribute = storedProcedurePropertyInfo.GetCustomAttribute ();'(自.NET 4.5(2012)以來的擴展方法,需要'使用System.Reflection;')看起來更好。 –