2011-06-10 59 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)并完成工作。