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;
    }
}

how do I achieve this? OR any work around?

有帮助吗?

解决方案

You can't, it doesn't make sense.

the settings action you pass to StartUpMethod is typed to Derived and will be entitled to use the interface of SettingsDerived. You can't then give it a base class and expect it to just handle it.

eg, if I have...

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

I'm entitled to do :-

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

but in the method1 you are trying to give it a SettingsBase s = new SettingsBase();

which won't have the DerivedSetting

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top