2010-03-26 3 views

답변

5

당신은 인터페이스를 구현하는 몇 가지 유형의 새로운 인스턴스를 생성하고이 같은 것을 할 수있는 몇 가지 데이터를 전달하려는 경우

public static string MyMethod<T>(object dataToPassToInterface) where T : IMyTypeOfInterface, new() 
{ 
    T instance = new T(); 
    return instance.HandleData(dataToPassToInterface); 
} 

과 같이 호출 :

string s = MyMethod<ClassImplementingIMyTypeOfInterface>(data); 
2

인터페이스를 인스턴스화 할 수 없습니다. 인터페이스를 구현하는 클래스 만 인스턴스화 할 수 있습니다.

public static string MyMethod<T>(object dataToPassToInterface) 
    where T : IMyTypeOfInterface 
{ 
    // an instance of IMyTypeOfInterface knows how to handle 
    // the data that is passed in 
} 

그러나 결코는 "인터페이스의 인스턴스를"할 수있을 것입니다 :

1

당신은 IMyTypeOfInterface를 구현 뭔가 것에 유형 매개 변수를 제약 조건 수 있습니다.

0

당신을 인터페이스를 인스턴스화 할 수는 없지만 generic 매개 변수로 전달 된 유형이 인터페이스를 구현하는지 확인하십시오.

public static string MyMethod<T>(object dataToPassToInterface) 
     where T : IMyTypeOfInterface 
    { 
     // an instance of IMyTypeOfInterface knows how to handle 
     // the data that is passed in 
    } 
관련 문제