以下示例在Java中给出. Create方法需要一个接口实现.但是,我还没有意识到在仍然访问类范围变量时覆盖接口的’onCreated’方法的类似方法.这是我遇到麻烦,我怎么能在C#中做到以下几点.
Java的:
private static barcodeReader barcodeReader;private AIDcManager manager;public voID onCreate(Bundle savedInstanceState) { // create the AIDcManager provIDing a Context and a // CreatedCallback implementation. AIDcManager.create(this,new CreatedCallback() { @OverrIDe public voID onCreated(AIDcManager aIDcManager) { manager = aIDcManager; barcodeReader = manager.createbarcodeReader(); } });}
在.NET中,编译器不会像上面那样执行并将接口实现为匿名类型,因此我必须实现接口.但是,我怎么能分配类宽变量?
我的C#:
nameSpace Scanner { private static barcodeReader barcodeReader; private AIDcManager manager; protected overrIDe voID OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our vIEw from the "main" layout resource SetContentVIEw(Resource.Layout.Main); CreateCallback callback = new CreateCallback() { }; AIDcManager.Create(this,callback.OnCreated(AIDcManager aIDcManager)); }public class CreateCallback : AIDcManager.ICreatedCallback{ public IntPtr Handle { get { throw new NotImplementedException(); } } public voID dispose() { throw new NotImplementedException(); } public voID OnCreated(AIDcManager p0) { // How can I initialize the manager and barcode reader variables in the class above from here? } }}解决方法 您可以创建一个回调实现CreateCallback,它具有另一个回调作为构造函数参数successAction.传递回调的OnManagerCreated将在OnCreated的CreateCallback中调用.
重要说明:如果实现Java接口,则必须从java.lang.Object继承.不要自己实现Handle和dispose().
活动
public class MyActivity : Activity { private static barcodeReader _barcodeReader; private AIDcManager _manager; protected overrIDe voID OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our vIEw from the "main" layout resource SetContentVIEw(Resource.Layout.Main); CreateCallback callback = new CreateCallback(OnManagerCreated) { }; AIDcManager.Create(this,callback); } private voID OnManagerCreated(AIDcManager manager) { _manager = manager; _barcodeReader = manager.CreatebarcodeReader(); }}
回调实现
public class CreateCallback : java.lang.Object,AIDcManager.ICreatedCallback{ private Action<AIDcManager> _successAction; public CreateCallback(Action<AIDcManager> successAction) { _successAction = successAction; } public voID OnCreated(AIDcManager p0) { _successAction(p0); }}
其他可能性
您也可以直接在您的活动类中实现界面
public class MyActivity : Activity,AIDcManager.ICreatedCallback { // ...}总结
以上是内存溢出为你收集整理的接口实现C#与Java的差异全部内容,希望文章能够帮你解决接口实现C#与Java的差异所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)