2012-07-25 9 views
6

我正在實現一個接口,以便將自定義業務邏輯注入到利用Microsoft Unity的框架中。我的核心問題是,我需要實現的接口定義了以下方法:實現與通用類型的接口,這種通用類型比我需要調用的方法更少約束

T InterfaceMethod<T>(); 

T沒有限制。在我的代碼,我需要從不同的第三方庫調用一個方法,用

T AnotherMethod<T>() where T: class; 

類型T的方法簽名是的AnotherMethod邏輯顯著。有沒有辦法在我的實現中調用AnotherMethod<T>(),而不使用反射?如果T是值類型,我顯然需要採取替代操作。有沒有辦法解決這個問題?

+0

是什麼AnotherMethod ()做有T?如果你想打開它,只需先將它投射到一個物體上。? – 2012-07-25 02:05:26

+0

不知道這對我有幫助,因爲我收到了關於T需要成爲引用類型的編譯錯誤。 – techphoria414 2012-07-25 02:13:27

回答

1

我不認爲你正在尋找的是沒有反思的可能。充其量,您可以撥打AnotherMethod<object>()並投下結果。但是,如果AnotherMethodT對您的目的不重要,那麼這隻能真正起作用。

+0

看來,在我的情況下,你是正確的。 – techphoria414 2012-07-26 17:59:52

2

我不確定這正是你所需要的,但是這可以讓你在不使用反射的情況下從InterfaceMethod調用AnotherMethod。它仍然使用Convert.ChangeType。

這個想法是通過約束(這裏是Tin)來實現泛型類的實現。然後,將InterfaceMethod的無約束類型T轉換爲Tin。最後,您可以使用約束類型調用AnotherMethod。以下工作正常與字符串。

public interface ITest 
{ 
    T InterfaceMethod<T> (T arg); 
} 

public interface ITest2 
{ 
    U AnotherMethod<U>(U arg) where U : class; 
} 

public class Test<Tin> : ITest, ITest2 where Tin : class 
{ 
    public T InterfaceMethod<T> (T arg) 
    { 
     Tin argU = arg as Tin; 
     if (argU != null) 
     { 
      Tin resultU = AnotherMethod(argU); 
      T resultT = (T)Convert.ChangeType(resultU,typeof(T)); 
      return resultT; 
     } 
     return default(T); 
    } 

    public U AnotherMethod<U> (U arg) where U : class { return arg; } 
} 
+0

+1爲獨創性,但不幸的是隨着我的類需要由框架代碼中的Unity實例化,我不能在類本身上使用泛型。編輯我的問題來澄清一些情況。絕對可以爲那些能夠在實例化類時指定的人工作。 – techphoria414 2012-07-26 16:53:45

0

什麼其他人說的是,你可以通過對象是這樣的:

public interface ITest 
{ 
    T InterfaceMethod<T>(T arg); 
} 

public interface IAnotherTest 
{ 
    U AnotherMethod<U>(U arg) where U : class; 
} 

public class Test : ITest 
{ 
    private IAnotherTest _ianothertest; 

    public T InterfaceMethod<T>(T arg) 
    { 
     object argU = arg as object; 
     if (argU != null) 
     { 
      object resultU = _ianothertest.AnotherMethod(argU); 
      T resultT = (T)Convert.ChangeType(resultU, typeof(T)); 
      return resultT; 
     } 
     return default(T); 
    } 
} 
+0

正如Tim S指出的那樣,只有當T的類型對被調用的方法不重要時纔有效。不幸的是。 – techphoria414 2012-07-26 17:59:25

相關問題