You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将登录页用户信息传递到主页,及解决User.Picture非静态引用报错

Error An object reference is required for the non-static field, method, or property 'User.Picture'

错误原因

  • 你定义的User类中Picture、Id、Name等属性都是实例属性,必须通过User类的实例对象访问,不能直接用类名User调用
  • 你在LoginPage中反序列化得到的user实例没有传递到HomePage,HomePage无法直接获取登录后的用户数据
  • 额外注意:User类中定义的ID字段属性名为Id(首字母小写i),你代码中写的User.ID大小写不匹配,也会触发报错

修复方案

方案1:构造函数传参(适合你注释中的页面跳转逻辑)

  1. 修改HomePage构造函数,增加User类型参数接收登录用户实例
public partial class HomePage : ContentPage
{
    public HomePage(User user)
    {
        InitializeComponent();
        PictureImage.Source = user.Picture;
        IdLabel.Text = user.Id;
        NameLabel.Text = user.Name;
        // 其余逻辑保持不变
     }
}
  1. 修改LoginPage跳转逻辑,把获取到的user实例传入HomePage
if (user != null)
{
    App.Current.MainPage = new NavigationPage(new HomePage(user));
}

方案2:全局静态变量存储(适合Shell路由跳转场景)

  1. 修改AuthenticationState类,增加静态属性存储当前登录用户
public class AuthenticationState
{
    public static OAuth2Authenticator Authenticator;
    public static User CurrentLoginUser { get; set; }
}
  1. LoginPage获取到用户实例后先赋值给全局静态属性
if (user != null)
{
    AuthenticationState.CurrentLoginUser = user;
    var route = $"{ nameof(HomePage)}";
    await Shell.Current.GoToAsync(route);
}
  1. HomePage直接访问全局静态属性即可
public HomePage()
{
    InitializeComponent();
    PictureImage.Source = AuthenticationState.CurrentLoginUser.Picture;
    IdLabel.Text = AuthenticationState.CurrentLoginUser.Id;
    NameLabel.Text = AuthenticationState.CurrentLoginUser.Name;
}

内容的提问来源于stack exchange,提问作者Star Gates

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 06:45:04