2011-06-10 58 views
1

我正在檢修一些代碼,並且遇到了一些障礙。擴展方法和泛型 - 我應該怎麼做?

這是我現在有方法中,它需要再加工,以支持一些結構的變化:完全贊成已知_Control擴展方法被移除

/// <summary> 
/// Recreates a dashboard control based off of its settings. 
/// </summary> 
/// <typeparam name="T"> The type of control to be recreated. </typeparam> 
/// <param name="settings"> The known settings needed to recreate the control.</param> 
/// <returns> The recreated control. </returns> 
public static T Recreate<T>(ISetting<T> settings) where T : new() 
{ 
    T _control = new T(); 
    settings.SetSettings(_control); 
    Logger.DebugFormat("Recreated control {0}", (_control as Control).ID); 
    return _control; 
} 

ISetting。

所以,我現在有:

public static class RadControlExtensions 
{ 
    public static RadDockZoneSetting GetSettings(this RadDockZone dockZone) 
    { 
     RadDockZoneSetting radDockZoneSetting = new RadDockZoneSetting(dockZone.UniqueName, dockZone.ID, dockZone.Skin, dockZone.MinHeight, 
      dockZone.HighlightedCssClass, dockZone.BorderWidth, dockZone.Parent.ID); 

     return radDockZoneSetting; 
    } 

    public static RadTabSetting GetSettings(this RadTab tab, int index) 
    { 
     RadTabSetting radTabSetting = new RadTabSetting(tab.Text, tab.Value, index); 
     return radTabSetting; 
    } 

    //Continued 
} 

正在被重新保證具有這種擴展方法控制

我現在是(將是不錯的強制執行這一點,雖然)。 :

public static T Recreate<T>() where T : new() 
{ 
    T _control = new T(); 
    //Not right -- you can't cast a control to an extension method, obviously, but 
    //this captures the essence of what I would like to accomplish. 
    (_control as RadControlExtension).SetSettings(); 
    Logger.DebugFormat("Recreated control {0}", (_control as Control).ID); 
    return _control; 
} 

如果可能的話,我應該尋找哪些支持?

回答

0

如果您知道獲取傳遞將是一個RadDockZone(或源自RadDockZone)每_control只是這樣做:

T _control = new T(); 
(RadDockZone)_control.SetSettings(); 
Logger.DebugFormat("Recreated control ... //rest of code here 

如果它不總是將是一個RadDockZone,你需要做的一些類型檢查以獲得正確的類型來調用擴展方法。我假設,在那裏,您可以將所有可能的類型傳遞給您的重建方法的.SetSettings()擴展方法。

+0

該場景是階梯 - 我會嘗試,我只是想確保我沒有錯過簡單的解決方案。謝謝! – 2011-06-10 21:31:40

0

您需要將T轉換爲您的擴展方法所支持的內容。

(_control as RadDockZone).GetSettings

擴展方法上的一種類型,他們不是傳統意義上的類型進行操作。 'SomeFn(字符串this)'使得你的擴展工作的東西是字符串,它是字符串和從它們派生的任何東西。

0

如果我理解正確的話你正在嘗試做的,只是把一個約束上T

public static T Recreate<T>() where T : RadControl, new() { 
    // etc. 
} 

您可能需要使用雙調度和定義

public static RadControl GetSettings(this RadControl control) { 

} 

將調用適當的GetSettings方法。

+0

直到「WebControl」和使用我的方法擴展WebControl時感覺不正確,看起來好像沒有一個好的公共基礎。首先看看AllenG的建議,看看是否合適。 – 2011-06-10 21:32:40

0

不,傑森的回答是更清潔的方式。被接受的解決方案殺死了類型安全,並且使用泛型沒有意義。您可以切換到通用設計(具有RadControlFactory)並完成工作。