我有一个必须扩展的类Activity
,例如
BaseActivity : Activity { }
和另一个必须扩展的类ListActivity
,例如
BaseListActivity : ListActivity {} // ListActivity in turn extends Activity
这两个类都有一些相同的方法,例如
OnCreate(Bundle bundle), OnStart(), OnStop()
两者的实现完全相同,例如
BaseActivity : Activity {
public bool isBound = false;
public MyServiceBinder binder;
MyServiceConnection _myServiceConnection;
MyReceiver _myReceiver;
internal Intent _myServiceIntent;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
_myServiceIntent = new Intent(this, typeof(MyServiceCls));
_myReceiver = new MyReceiver();
_myServiceConnection = LastNonConfigurationInstance as MyServiceConnection;
if (_myServiceConnection != null)
binder = _myServiceConnection.Binder;
}
protected override void OnStart()
{
base.OnStart();
var intentFilter = new IntentFilter(MyServiceCls.MyUpdatedAction) { Priority = (int)IntentFilterPriority.HighPriority };
RegisterReceiver(_myReceiver, intentFilter);
_myServiceConnection = new MyServiceConnection(this);
Application.Context.BindService(_myServiceIntent, _myServiceConnection, Bind.AutoCreate);
StartService(_myServiceIntent);
}
protected override void OnStop()
{
base.OnStop();
if (isBound)
{
Application.Context.UnbindService(_myServiceConnection);
isBound = false;
}
StopService(_myServiceIntent);
UnregisterReceiver(_myReceiver);
}
}
和
BaseListActivity : ListActivity {
public bool isBound = false;
public MyServiceBinder binder;
MyServiceConnection _myServiceConnection;
MyReceiver _myReceiver;
internal Intent _myServiceIntent;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
_myServiceIntent = new Intent(this, typeof(MyServiceCls));
_myReceiver = new MyReceiver();
_myServiceConnection = LastNonConfigurationInstance as MyServiceConnection;
if (_myServiceConnection != null)
binder = _myServiceConnection.Binder;
}
protected override void OnStart()
{
base.OnStart();
var intentFilter = new IntentFilter(MyServiceCls.MyUpdatedAction) { Priority = (int)IntentFilterPriority.HighPriority };
RegisterReceiver(_myReceiver, intentFilter);
_myServiceConnection = new MyServiceConnection(this);
Application.Context.BindService(_myServiceIntent, _myServiceConnection, Bind.AutoCreate);
StartService(_myServiceIntent);
}
protected override void OnStop()
{
base.OnStop();
if (isBound)
{
Application.Context.UnbindService(_myServiceConnection);
isBound = false;
}
StopService(_myServiceIntent);
UnregisterReceiver(_myReceiver);
}
}
区别在于两者的用法。例如
MyActivity : BaseActivity
{ /* this overrides the methods and does things differently */}
和
MyListActivity : BaseListActivity
{ /* this overrides the methods and does things differently */}
最终我的问题是我不想在BaseActivity
andBaseListActivity
类中复制相同的代码。解决此问题的最佳方法是什么,我仍然可以拥有执行所需功能所需的覆盖,而无需重复代码?
注意:你们中的一些人可能认为这是一个 Android 项目 - 确实如此。它是用 Xamarin(又名 Monodroid)构建的,这就是它在 C# 中的原因。