2014-09-27 2 views
0

저는 C#을 처음 접했고 명확한 답을 찾을 수없는 문제가 발생했습니다.유형을 매개 변수로 전달하고이를 함수의 변수 유형을 선언하는 데 사용할 수 있습니까?

본인은 기본 클래스가 "엔터티"입니다. 이 클래스는 여러 "엔티티"에 의해 확장됩니다. 현재 데이터베이스에서 "Entities"를로드하는 방법을 알고있는 함수가 있습니다. 이 모든 함수를 데이터베이스에서 기본 클래스 "Entity"를로드하는 방법을 알고있는 하나의 함수로 바꾸려고합니다.

"TestPlan"유형 하나만로드하는 방법을 알고있는 함수의 예입니다.

public List<TestPlan> LoadTestPlans() 
    { 
     List<TestPlan> testPlans = new List<TestPlan>(); 
     using (ITransaction transaction = session.BeginTransaction()) 
     { 
      testPlans = (List<TestPlan>)session.CreateCriteria<TestPlan>().List<TestPlan>(); 
      transaction.Commit(); 
     } 
     return testPlans; 
    } 

저는 이것을 다음과 같이 바꾸고 싶습니다. 그러나 형 변환에 적합한 주문을 이해할 수 없습니다.

public List<Entity> LoadEntities(Type entityType) 
    { 

     List<entityType> entities= new List<entityType>(); 
     using (ITransaction transaction = session.BeginTransaction()) 
     { 
      entities= (List<entityType>)session.CreateCriteria<entityType>().List<entityType>(); 
      transaction.Commit(); 
     } 
     return entities; 
    } 

제네릭 형식의 목록으로 몇 가지를 보았습니다. 어떻게 작동하는지 잘 모르겠습니다. 나는 제네릭 타입 루트를 내려가는 것이 조금 주저합니다. 난 당신이 전달 된 잘못된 유형의 함수를 호출하려고하면 시간이 오류를 컴파일 할

답변

1

당신은 일반적인 방법을 사용할 수 있습니다.이 코드를 사용할 때 유형을 제공해야

public List<T> LoadEntities<T>() where T: Entity 
{ 

    List<T> entities= new List<T>(); 
    using (ITransaction transaction = session.BeginTransaction()) 
    { 
     entities= (List<T>)session.CreateCriteria<T>().List<T>(); 
     transaction.Commit(); 
    } 
    return entities; 
} 

을 당신을 욕망 대신 T.

+0

docs : http://msdn.microsoft.com/en-us/library/bb384067.aspx – Miebster

관련 문제