2016-10-22 8 views
0

모든 클래스에서 기본 필드 값을 반환하는 메소드를 만들었습니다. 값을 얻으려고 Reflection을 사용하려하지만 작동하지 않습니다. 나는 저 클래스의 이름을 전달, 희망 원하는 필드 값을 얻을 수 있습니다이 방법이리플렉션은 C#에서 사용자 정의 클래스를 얻지 못합니다.

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; } 
    } 
} 

: 여기

내가 원하는 기본값 ( StoredProcedure)가있는 클래스 :

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에 클래스의 정규화 된 정규화 된 이름을 전달합니까? 네임 스페이스가 어셈블리와 일치한다고 가정하면 "Services.Data.Report.PayrollReport, Services.Data.Report"라는 "namespace.classname, assemblyname"이어야합니다. 이를 확인하기 위해 클래스에서 이것을 실행하고 출력을 캡처 할 수 있습니다 : 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

'% deafultValueAttribute = storedProcedurePropertyInfo.GetCustomAttribute ();'(.NET 4.5 (2012) 이후의 확장 메서드는'using System.Reflection; '을 사용하는 것이 낫습니다). –