2014-02-12 3 views
0

System.Data.Services.Client.DataServiceContext에서 파생되는 특정 종류의 클래스를 검색하기 위해 제네릭 메서드를 만들 필요가 있습니다.이 문제를 처리하는 방법이 있지만 지금까지는 고생하고 있습니다. 일반적인 공통 분모의 개념은이 개념이이 경우에 적용됩니까? 이처럼 내 현재 코드는 모습입니다 : 당신이 볼 수 있듯이, 내가 선택적 매개 변수와 T를 인스턴스화 할 수있는 방법은 없습니다여러 DataContext에 대한 제네릭 메서드를 만드는 아이디어

public abstract class BaseODataProvider<T> where T : DataServiceContext, new() 
{ 
    public IApiSettings ApiSettings { get; set; } 

    public BaseODataProvider(IApiSettings ApiSettings = null) 
    { 
     this.ApiSettings = ApiSettings ?? new DefaultApiSettings(); 
    } 

    public T GetContext() 
    { 
     var context = new T(new Uri(ApiSettings.ODataUrl)); 
     context.IgnoreMissingProperties = true; 
     context.IgnoreResourceNotFoundException = true; 
     var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(ApiSettings.LoginName + ":" + ApiSettings.Password)); 
     context.SendingRequest += 
       (object s, SendingRequestEventArgs e) => 
         e.RequestHeaders.Add("Authorization", "Basic " + credentials); 
     return context; 
    } 
} 

, 그것은 그러나 내가 해결할 수있는 방법을 찾아 싶다 "cannot provide parameters when creating an instance of a type parameter 'T'"라고

GetContext<MyContext1>().Table1.Where(x=>x.Id == 1); 
GetContext<MyContext2>().Table2.FirstOrDefault(); 

어떤 도움 작동 : URI가, T의 유형에 따라 oDataContext를 만드는 데 필요한 것을 나의 예상되는 경우는 다음과 같이 될 것입니다!

+0

무엇을 하시겠습니까? 당신이 말했듯이 제네릭 타입의 매개 변수를 가진 생성자를 사용할 방법이 없습니다. – MarcinJuraszek

+0

"new() 제약"제한뿐만 아니라이 문제에 대한 해결 방법이있을 경우 조언을 권합니다. Lambda Expressions를 사용하여 T의 인스턴스를 만드는 방법이 있습니까? 다시, ctor에 매개 변수가 있습니까? –

답변

1

리플렉션을 사용하여 매개 변수가있는 제네릭 형식의 개체를 인스턴스화 할 수 있습니다.

public T GetContext() 
{ 
    Uri myUri = new Uri(ApiSettings.ODataUrl); 

    Type contextType = typeof(T); 
    DataServiceContext context = (T)Activator.CreateInstance(contextType, myUri); 

    // Do whatever 

    return context; 
} 

Activator.CreateInstance의 두 번째 인수는 유형 object의 배열입니다, 그래서 당신은 어떤 번호 또는 생성자가 필요 인수의 형태로 전달할 수 있습니다. 이와 생성자 작동 - 당신이 중 하나의 매개 변수로 제한하지 않는

public class MyContext1 : DataServiceContext 
{ 
    public MyContext1(Uri uri) 
    { 
     // Do whatever 
    } 
} 

public class MyContext2 : DataServiceContext 
{ 
    public MyContext2(Uri uri) 
    { 
     // Do whatever 
    } 
} 

: 위의 코드를 작동하게하려면 사용하는 T 모든 유형이 같은 동일한 서명을 가진 생성자를 가질 필요가 임의의 수의 매개 변수. 이런 식으로 인스턴스화하는 각 클래스에 대해 동일한 수와 유형의 인수를 사용하고 있는지 확인하십시오.