1
public class SettingsBase
{

}
public class SettingsDerived : SettingsBase
{

}
public class yyy
{
    public void StartUpMethod(Action<SettingsDerived> settings)
    {
        //something goes here..
        SettingsDerived ds = new SettingsDerived();
        settings(ds);//take out SettingsDerived properties..
        SettingsBase bs = Method1(settings as Action<SettingsBase>);//as operator returns null because settings is not of type Action<SettingsBase>
        //again do something on s based on extracted SettingsDerived

    }

    public SettingsBase Method1(Action<SettingsBase> settings)
    {
        SettingsBase s = new SettingsBase();
        //something goes here
        settings(s);
        return s;
    }
}

我该如何做到这一点?或任何解决方法?

4

1 回答 1

6

你不能,这没有意义。

您传递给的设置操作StartUpMethod被输入到 Derived 并且将有权使用 SettingsDerived. 然后你不能给它一个基类并期望它只处理它。

例如,如果我有...

public class SettingsDerived : SettingsBase
{
   public string DerivedSetting { get; set; }
}

我有权这样做:-

y.StartUpMethod( a => a.DerivedSetting = "blah" );

但在 method1 中,你试图给它一个SettingsBase s = new SettingsBase();

不会有DerivedSetting

于 2013-05-24T04:39:06.320 回答