C# 扩展方法和泛型-我应该怎么做? 我正在翻修一些代码,我遇到了一点困难。

C# 扩展方法和泛型-我应该怎么做? 我正在翻修一些代码,我遇到了一点困难。,c#,generics,refactoring,C#,Generics,Refactoring,这是我目前使用的方法,需要重新设计以支持某些结构更改: /// <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">

这是我目前使用的方法,需要重新设计以支持某些结构更改:

/// <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;
}
正在重新创建的控件保证具有此扩展方法,不过,强制执行此方法会很好

我现在在:

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;
}
如果可能的话,我应该研究什么来支持这一点?

如果您知道传递的每个_控件都是RadDockZone或从RadDockZone派生的,请执行以下操作:

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

如果它不总是RadDockZone,那么需要进行一些类型检查,以获得调用扩展方法的正确类型。我假设,在所有可能传递给create方法的类型上都有一个.SetSettings扩展方法。

您需要将T转换为扩展方法支持的类型

_控件为RadDockZone.GetSettings


扩展方法操作的是一种类型,而不是传统意义上的类型。“SomeFnstring this”使您的扩展可以处理字符串以及从字符串派生的任何内容

如果我正确理解了您要做的事情,只需对T进行约束:


这将调用相应的GetSettings方法。

不,Jason的答案更简洁。被接受的解决方案消除了类型安全性,并使泛型的使用变得毫无意义。您可以使用RadControlFactory切换到通用的非通用设计,并完成工作。

场景是阶梯-我会尝试,我只是想确保我没有错过一个简单的解决方案。谢谢在WebControl和使用我的方法扩展WebControl感觉不正确之前,看起来没有一个好的公共基础。我会先看看阿伦的建议,看看这是否正确。
T _control = new T();
(RadDockZone)_control.SetSettings();
Logger.DebugFormat("Recreated control ... //rest of code here
public static T Recreate<T>() where T : RadControl, new() {
    // etc.
}
public static RadControl GetSettings(this RadControl control) {

}