2014-03-05 2 views
0

I는 다음과 같습니다 서명이있는 방법이 있습니다어떻게 제네릭 형식 문자열을 변환하는

public IList<T> GetReferenceData<T>(TransactionManager transactionManager = null) 
{ 
    IList<T> collection; 
    var cacheData = DataCacheManager.Instance.GetCacheItem(typeof(T).Name); 
    if (cacheData != null) 
    { 
     collection = (IList<T>)cacheData; 
    } 
    else 
    { 
     collection = this.GetReferenceDataNoCache<T>(transactionManager); 
     DataCacheManager.Instance.AddCacheItem(typeof(T).Name, collection); 
    } 

    return collection; 
} 

나는 나를에 해당 문자열을 변환하는 문자열에 전달할 수 있습니다 다른 방법이 적절한 유형. 그런 다음 위의 메서드를 호출하고 싶습니다.

public IList GetReferenceDataByType(string referenceType) 
{ 
     // this works and returns the appropriate type correctly 
     var type = this.GetEntity(referenceType); 

     // now I'm stuck 
     return this.GetReferenceData<?>(); 
} 

무엇이 물음표를 대체합니까?

public IList GetReferenceDataByType(string referenceType) 
{ 
     // this works and returns the appropriate type correctly 
     var type = this.GetEntity(referenceType); 

     var method = this.GetType().GetMethod("GetReferenceData"); 
     var generic = method.MakeGenericMethod(type); 
     return (IList) generic.Invoke(this, new object[] { null }); 
} 

IList<T> 즉, 그래서 캐스트가 실패 할 수 있습니다 IList를 구현하지 않습니다

+2

을 도움이되기를 바랍니다. –

+1

@TimSchmelter 이것은 문제가되지 않습니다. 그는 이미 그 유형을 가지고 있습니다. 그는 변수 유형 매개 변수를 기반으로 완전히 해결 된 제네릭 메소드를 얻고 싶습니다. –

+0

'GetReferenceData '본문을 게시 할 수 있습니까? – Dennis

답변

1

나는 당신의 질문을 이해하면 올바르게은 다음과 같이 somethiong합니다.

+0

"매개 변수 개수가 일치하지 않습니다."오류가 발생합니다. – Junto

+0

일반 호출이 기본 매개 변수를 감지하지 못할 수 있으므로 업데이트 된 답변을 시도하십시오. – Magnus

+0

빙고. 그거야. 고맙습니다. – Junto

0

당신의 접근 방식을 뒤집어 놓아야합니다. 대신 제네릭이 아닌 대안에서 일반적인 방법을 호출
는, 당신은 GetReferenceDataGetReferenceDataNoCache는 제네릭이 아닌 사람으로 다시 작성해야합니다

public IList GetReferenceData(Type type, TransactionManager transactionManager = null) 
{ 
    // ... 
} 

private IList GetReferenceDataNoCache(Type type, TransactionManager transactionManager = null) 
{ 
    // ... 
} 

public IList<T> GetReferenceData<T>(TransactionManager transactionManager = null) 
{ 
    return (IList<T>)GetReferenceData(typeof(T), transactionManager); 
} 

봐 코드에서 : GetReferenceData<T>에서 T의 유일한 장점은 typeof(T)입니다.
나머지 메소드는 사실 제네릭이 아닙니다.

+0

좋은 지적이 있지만 50 개가 넘는 참조 테이블이 있습니다. 제네릭은 상당한 양의 코드를 저장합니다. – Junto

+0

테이블의 양은 메소드 구조와 관련이 있습니까? – Dennis

+0

죄송합니다. 귀하의 답변을 오해했습니다. 나는 당신이 50 개 이상의 별도의 GetReferenceData (TypeX typeX ... 선언문이 필요함을 암시한다고 생각했다. – Junto