简体   繁体   English

可以使用monodroid重载活动默认构造函数吗?

[英]Can an activity default constructor be overloaded with monodroid?

In standard C#, I can overload the default constructor with something like 在标准的C#中,我可以用类似的东西重载默认构造函数

public class foo
{
  data bar;
  public foo(data bar)
  {
     this.bar = bar;
  }
}

Is there a way I can do this in monodroid? 有没有办法在monodroid中做到这一点? I'm trying to overload a default constructor in an activity (just to make it fun!). 我正在尝试重载一个活动中的默认构造函数(只是为了让它变得有趣!)。

Can you provide an Activity constructor which takes parameters? 你能提供一个带参数的Activity构造函数吗? Yes. 是。 Would it be at all helpful? 它会有用吗? No, because Activities are started through Context.StartActivity() , which provides no mechanism to invoke a non-default constructor. 不,因为活动是通过Context.StartActivity()启动的,它没有提供调用非默认构造函数的机制。

The "Android Way" to transfer data between Activities is to use the Intent "extras" mechanism, eg Intent.PutExtra(string,string) and Intent.GetStringExtra(string) , which introduces it's own set of problems: 在Activities之间传输数据的“Android Way”是使用Intent“extras”机制,例如Intent.PutExtra(string,string)Intent.GetStringExtra(string) ,它引入了它自己的一组问题:

  1. Intents are also an IPC mechanism (as an Activity may actually reside in another process -- this is by design), so you're restricted to types which can be marshaled across process boundaries. 意图也是一种IPC机制(因为一个Activity实际上可能存在于另一个进程中 - 这是设计的),所以你只能被限制为可以跨进程边界编组的类型。
  2. String s, int s, and other builtin types are supported, but aren't exactly "high level" objects. String s, int和其他内置类型,但不完全是“高级”对象。
  3. "Higher level" objects are supported through the android.os.Parcelable interface, but (a) has a "marshal by value" semantic, so isn't useful for sharing read+write data between activities, and (b) Mono for Android doesn't currently support implementing this interface . 通过android.os.Parcelable接口支持“更高级别”对象,但(a)具有“按值分组”语义,因此对于在活动之间共享读取和写入数据没有用,并且(b) Mono for Android目前不支持实现此接口

So how do you share data between Activities? 那么如何在活动之间共享数据? By punting. 通过撑船。

  • Place the data onto an Application subclass. 将数据放在Application子类上。 This will be accessible via the Context.ApplicationContext property, and can store process-global state. 这可以通过Context.ApplicationContext属性访问,并且可以存储进程全局状态。
  • Use some other public static field within your process to contain the shared information. 使用进程中的某些其他public static字段来包含共享信息。
  • Provide a ContentProvider implementation which will store and provide the desired data when prompted. 提供ContentProvider实现,该实现将在提示时存储并提供所需的数据。
  • Sqlite? SQLite的?
  • etc. 等等

You don't implement constructors in activities in Android. 您没有在Android中的活动中实现构造函数。 Please perform this sort of initialization in onCreate() , after calling super.onCreate() . 请在调用super.onCreate()之后在onCreate()执行此类初始化。

(my apologies for the Java syntax -- I don't speak C#) (我为Java语法道歉 - 我不会说C#)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM