Reputation: 965
I have two abstract classes
public abstract class PluginBase
{
protected SettingBase LocalSettings { get; set; }
}
public abstract class SettingBase
{
}
I am then creating a new class using PluginBase, and along with it I create a class using SettingBase
public class MyPlugin : PluginBase
{
}
public class MySettings : SettingBase
{
public string MyValue;
}
I then load an instance of "MySettings", into the "LocalSettings" property.
Within MyPlugin I would then like to access the "MyValue" property of the "LocalSettings" property. I know I can access it like this;
((MySettings)LocalSettings).MyValue;
But I am looking for a nicer way to do this, preferably without the need to constantly reference the new type every time, something like this;
MyLocalSettings.MyValue
I would ideally like to avoid referencing properties with any string based methods.
Upvotes: 0
Views: 78
Reputation: 177
Could generics work for you maybe?
public abstract class PluginBase
{
// move it to the generic base class
// protected SettingBase LocalSettings { get; set; }
}
public abstract class PluginBase<TSettings> : PluginBase where TSettings : SettingBase
{
protected TSettings LocalSettings { get; set; }
}
public abstract class SettingBase
{
}
public class MyPlugin : PluginBase<MySettings>
{
public void DoIt()
{
Console.WriteLine(this.LocalSettings.MyValue);
}
}
public class MySettings : SettingBase
{
public string MyValue;
}
Upvotes: 5
Reputation: 48230
Just make SettingsBase
actually contract anything than just emptiness:
public abstract class SettingBase
{
public abstract object GetSettingValue( string settingName );
}
This imposes an obligation for the implementor
public class MySettings : SettingBase
{
public override object GetSettingValue( string settingName )
{
switch (settingName)
{
case "MySetting": ...
but gives a Chance to the client to use the obligation
this.LocalSettings.GetSettingValue( "MySetting" );
without any cast to specific implementation type.
Upvotes: 0