2010-09-15 83 views
0
namespace Test 
{ 
    #region Not my code 
    public interface IAdditional 
    { 
    } 
    public interface ISome 
    { 
     ISomeOther<T> GetSomeother<T>() where T : class; 
    } 
    public interface ISomeOther<T> where T : class 
    { 
     void DoFoo(T obj); 
    } 
    public class AnotherClass<T> where T : class 
    { 
    } 
    public static class StaticClass 
    { 
     public static void DoBar<T>(AnotherClass<T> anotherClass, T obj) where T : class, IAdditional 
     { 
     } 
    } 
    #endregion 

    #region MyCode 
    public class SomeOtherImp<T> : ISomeOther<T> where T : class, IAdditional //Have to add IAdditional constraint to call StaticClass.DoBar 
    { 
     private AnotherClass<T> _anotherClass; 
     public void DoFoo(T obj) 
     { 
      StaticClass.DoBar<T>(_anotherClass, obj); //I do need to call StaticClass.DoBar here.... 
     } 
    } 
    public class ISomeImp : ISome 
    { 
     public ISomeOther<T> GetSomeother<T>() where T : class 
     { 
      return new SomeOtherImp<T>(); //Can't do this no IAdditional constraint on T 
     } 
    } 
    #endregion 
} 

我被迫加IAdditional到SomeOtherImp到能夠調用StaticClass.DoBar 現在我不能SomeOtherImp實現ISome ....C#調用泛型方法

+1

什麼是實際問題? – 2010-09-15 14:38:07

+0

如何從ISome.Get()實現的方法調用SomeStaticClass.Create 。 – 2010-09-15 14:47:41

+0

你能提供'ISomeInterface'的代碼嗎?你只給我們展示ISome。 – 2010-09-15 14:56:43

回答

1

你意味着你想能夠調用Get方法?如果你可以編輯界面ISome,試試這個:

public interface ISome 
{ 
    T Get<T>() where T:class, ISomeInterface 
} 

...否則你將不得不使用反射:

public class Foo : ISome 
{ 
    public T Get<T>() where T:class 
    { 
     if (!typeof(ISomeInterface).IsAssignableFrom(typeof(T))) throw new Exception(); 
     return (T)typeof(SomeStaticClass).GetMethod("Create").MakeGenericMethod(new [] {typeof(T)}).Invoke(); 
    } 
} 
+0

不幸的是我不能編輯ISome,SomeStaticClass – 2010-09-15 14:45:34

+0

我希望這可以在沒有反射的情況下用一些繼承魔法來完成..看起來不是。 – 2010-09-15 15:01:47

0

你可能只是這樣做

public class Foo : ISome 
{ 
    public T Get<T>() where T : class 
    { 
     return SomeStaticClass.Create<ISomeInterface>() as T; 
    } 
} 

如果它返回null,則傳入不是ISomeInterface的類型。

+0

看起來像我簡化了我的代碼actualy獲取()返回IBar 我應該編輯問題) – 2010-09-15 15:20:25

0

它看起來像你試圖實現工廠設計模式。看看下面的一段代碼。我從SomeClass的限制中刪除了接口。它編譯並將工作。在我看來,ISome及其實現Foo類已經過時了。

public static class SomeStaticClass 
{ 
    public static T Create<T>() where T:class 
    { 
     //Replace with actual construction of T 
     return (T)(new object()); 
    } 
} 

public interface ISome 
{ 
    T Get<T>() where T : class; 
} 

public class Foo : ISome 
{ 
    public T Get<T>() where T:class 
    { 
     return SomeStaticClass.Create<T>(); 
    } 
}