简体   繁体   English

如何使用实例化的 object 从一种方法到另一种方法?

[英]How to use an instantiated object from one method to another?

I have these two methods:我有这两种方法:

 public MessagesPage(ContactModel input)
        {
            InitializeComponent();
            NavigationPage.SetHasNavigationBar(this, false);
            ConversationsList = new ObservableCollection<ConversationModel>();
            ContactModel ConversationPartner = new ContactModel();
            ConversationPartner = input;
            ...
        }

And the input which is the parameter in the method above, I also would like to use it in this method (they're in the same class)而输入是上面方法中的参数,我也想在这个方法中使用它(它们在同一个类中)

 private async void Send()
        {
            Guid guid = Guid.NewGuid();
            string ID = guid.ToString();
            ConversationModel conversationObject = new ConversationModel()
            {
                id = ID,
                converseeID = dataClass.loggedInUser.uid,
                message = Message,
                created_at = DateTime.UtcNow
            };
            await CrossCloudFirestore.Current
                    .Instance
                    .GetCollection("contacts")
                    .GetDocument(ConversationPartner.id)
                    .GetCollection("conversations")
                    .GetDocument(ID)
                    .SetDataAsync(conversationObject);
            Message = string.Empty;
        }

because as you can see, in.GetDocument, it needs the id of ConversationPartner.因为如您所见,在 .GetDocument 中,它需要 ConversationPartner 的 ID。 I would get object reference not set to an instance of an object when the Send() method is called because it doesn't have access to ContactModel input in MessagesPage above.当调用 Send() 方法时,我会得到 object reference not set to an instance of an object ,因为它无权访问上面 MessagesPage 中的 ContactModel 输入。

you need to declare ConversationPartner as a class level variable, not inside of of a specific method.您需要将ConversationPartner声明为 class 级别变量,而不是在特定方法内部。 This will make it available throughout your class这将使它在您的整个 class 中可用

ContactModel ConversationPartner;

public MessagesPage(ContactModel input)
{
   InitializeComponent();
   NavigationPage.SetHasNavigationBar(this, false);
   ConversationsList = new ObservableCollection<ConversationModel>();
       
   ConversationPartner = input;
   ...
}

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

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