如何将Action <Derived>转换为Action <Base>

dot*_*ner 0 c# delegates as-operator

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎么做到这一点?或任何工作?

Kei*_*las 5

你不能,这没有意义.

您传递给的设置操作将StartUpMethod输入到Derived,并有权使用该界面 SettingsDerived.你不能给它一个基类,并期望它只是处理它.

例如,如果我有......

public class SettingsDerived : SettingsBase
{
   public string DerivedSetting { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我有权这样做: -

y.StartUpMethod( a => a.DerivedSetting = "blah" );
Run Code Online (Sandbox Code Playgroud)

但是在方法1中你试图给它一个 SettingsBase s = new SettingsBase();

哪个不会有 DerivedSetting

  • @dotNETbeginner:基思是对的; 如果你有一个苹果的方法,你不能把它变成一个拿水果的方法; 该方法采用Apple,但采用Fruit的方法可以使用Orange.你可以采取另一种方式:如果你有一个采用Fruit的方法,那么你可以把它变成一个苹果的方法,因为Apple是一个水果. (2认同)