我有两个抽象类
public abstract class PluginBase
{
protected SettingBase LocalSettings { get; set; }
}
public abstract class SettingBase
{
}
然后我使用PluginBase创建一个新类,并使用它创建一个使用SettingBase的类
public class MyPlugin : PluginBase
{
}
public class MySettings : SettingBase
{
public string MyValue;
}
然后我将" MySettings"的实例加载到" LocalSettings"属性。
在MyPlugin中,我想访问" MyValue" " LocalSettings"的属性属性。我知道我可以像这样访问它;
((MySettings)LocalSettings).MyValue;
但我正在寻找一种更好的方法来做到这一点,最好不需要每次都经常引用新类型,就像这样;
MyLocalSettings.MyValue
我希望避免使用任何基于字符串的方法引用属性。
答案 0 :(得分:5)
泛型可能会为你工作吗?
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;
}
答案 1 :(得分:0)
让SettingsBase
实际承包的不仅仅是空虚:
public abstract class SettingBase
{
public abstract object GetSettingValue( string settingName );
}
这对实施者施加了义务
public class MySettings : SettingBase
{
public override object GetSettingValue( string settingName )
{
switch (settingName)
{
case "MySetting": ...
但是让客户有机会使用义务
this.LocalSettings.GetSettingValue( "MySetting" );
没有任何强制转换为特定的实现类型。