我創建了一個方法來從任何類中返回默認的字段值。我正在嘗試使用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
的名字,並能夠訪問該字段,方法和其他屬性?
您是否在className中傳遞了該類的完整程序集限定名?它應該是「namespace.classname,assemblyname」,因此「Services.Data.Report.PayrollReport,Services.Data.Report」假定名稱空間與程序集匹配。爲了檢查你可以在類中運行它並捕獲輸出:this.GetType()。AssemblyQualifiedName – jimpaine
當你調用'GetDynamicReport'時,你期待什麼?在你的例子中,你是否期望得到值爲「report_payrollSummary」的字符串? – RVid
如果你想獲得'Property'的'Attribute'的值,你將需要獲得屬性(它不是一個字段)並使用反射來獲取屬性。 'ToString()'不會給你。見例如http://stackoverflow.com/q/6637679/224370 –