2014-10-01 49 views
0

創建T:與我有以下方法的兩個不同構造

public void Add<T>() where T : ISetup, new() { 
    new T().Run(); 
} // Add 

這可用於如下:

Add<SettingsSetup>() 

哪裏SettingsSetup是:

public class SettingsSetup : ISetup { 
    private Func<String, String> _resolver; 
    public SettingsSetup(Func<String, String> resolver) { 
    _resolver = resolver; 
    } 
    public void Run() { } 
} 

我想能夠使用Add如下:

Add<SettingsSetup>() 

或傳遞參數要在SettingsSetup使用:

Add<SettingsSetup>(Func<String, String>) 

這可能嗎?

+0

是什麼讓你覺得它不是?你是否嘗試簡單地編寫另一種方法重載? – 2014-10-01 21:12:23

+0

是的,我無法在Add方法中使用新的T(Func resolver) – 2014-10-01 21:13:27

+1

請記住,ISetup是一個接口...我可以將它作爲基類。基本上SettingsSetup或任何其他設置應允許使用使用Func 或什麼都沒有... – 2014-10-01 21:15:20

回答

1

一個Resolver屬性添加到ISetup,並從過載設置Add

public void Add<T>(Func<String, String> resolver) where T : ISetup, new() 
{ 
    var setup = new T(); 
    setup.Resolver = resolver; 
    setup.Run(); 
} 
+0

是的,這就是我在問題下面的評論中所說的。 – 2014-10-01 21:28:26

+0

請查看我的評論和鏈接,該鏈接位於Edit下方。有一個答案,但戴夫也是這樣做的。 – W92 2014-10-01 21:31:35

1

簡單:

public interface ISetup 
{ 
    void Run(); 
    int SomeProp { get; set; } 
} 

public class Setup : ISetup 
{ 
    public void Run() 
    { 
     throw new NotImplementedException(); 
    } 

    public int SomeProp 
    { 
     get 
     { 
      return 2; 
     } 
     set 
     { 
      SomeProp = value; 
     } 
    } 
} 

public bool MyMethod<T>(T t) where T : ISetup 
{ 
     return t.SomeProp != 2; 
} 

及用途:

var setup = new Setup(); 
bool response = MyMethod<Setup>(setup); // false 

編輯: 這裏的良好來源:http://msdn.microsoft.com/en-us/library/bb384067.aspx

相關問題