实现模板化接口

本文关键字:接口 实现 | 更新日期: 2023-09-27 17:58:57

我正试图更一般地写这篇文章:

public static CormantRadDock RecreateDock(RadDockSetting settings)
{
    CormantRadDock dock = new CormantRadDock();
    settings.SetSettings(dock);
    Logger.DebugFormat("Recreated dock {0}", dock.ID);
    return dock;
}

我有这个:

public static T Recreate<T>() where T : new()
{
    T _control = new T();
    //settings.SetSettings(dock);
    Logger.DebugFormat("Recreated control {0}", (_control as Control).ID);
    return _control;
}

通用解决方案:

public interface ISetting<T>
{
    void SetSettings(T obj);
}
public void SetSettings(CormantRadDock dock)
{
    // do stuff with dock
}

谢谢!

实现模板化接口

这就是您想要做的吗?

// move the generic type parameter up here so the interface is generic
// and not the method definition
public interface ISetting<T>
{
    void SetSettings(T obj);
}

然后你可以在一个类中成功地实现它:

public class SomeClass: ISetting<YourSettingType>
{
    public void SetSettings(YourSettingType obj) { ... }
}

任一

    public abstract class ISetting<T> 
{     
public abstract void SetSettings<T>(T obj); 
}  
public void SetSettings<T>(T dock) 
{     
// do stuff with dock 
} 

    public abstract class ISetting<T> 
{     
public abstract void SetSettings(T obj); 
}  
public void SetSettings(T dock) 
{    
 // do stuff with dock 
} 

这个怎么样:

public interface ICanBeRecreated<T>
{
    T Recreate();
}
public class CormantDock : ICanBeRecreated<CormantDock>
{
    private RadDockSetting _settings;
    private void ApplySettings(RadDockSetting settings)
    {
        // apply settings       
    }
    public CormantDock Recreate()
    {
        var dock = new CormantDock;
        dock.ApplySettings(_settings);
    }
}