Getter 和 setter 不工作,构造函数值保持为空 - ASP

Getter and setter not working, Constructor value stays empty - ASP

我有一个对象 'User' 的会话,我正在尝试将会话对象传递给 BLSecurity.cs。 class 使用用户对象检查登录状态和 return 布尔值。

问题是 'Gebruiker' 无论如何都保持为空。

BLSecurity.cs

public class BLSecurity {
    private wk_Gebruiker gebruiker;

    public wk_Gebruiker Gebruiker{
        get { return gebruiker; }
        set { gebruiker = value; }
    }

    public BLSecurity() {
    }

    public bool GebruikerIsIngelogd() {
        return Gebruiker != null;
    }

    public bool GebruikerIsAdmin() {
        return Gebruiker != null && Gebruiker.gebruikerniveauID == 1;
    }   
}

在我的 asp 项目的主文件中,我在加载函数中执行以下操作

protected void Page_Load(object sender, EventArgs e) {
    BLSecurity BLSecurity = new BLSecurity();

    wk_Gebruiker gebruiker = (wk_Gebruiker)Session["gebruiker"];
    if (gebruiker != null) {
        LabelTest.Text = gebruiker.voornaam;
    } else {
        LabelTest.Text = "no name";
    }
    BLSecurity.Gebruiker = gebruiker;

    ...
}

当用户登录时,他会看到带有标签 Test 的姓氏,当他注销时,他会看到 'no name'。所以那部分工作,但将它传递给 BLSecurity 肯定有问题。

感谢您的帮助!

啊,找到问题了

问题是我在需要函数 GebruikerIsIngelogd();

时创建了一个新的 BLSecurity 实例

所以我在加载函数中设置了 set 部分

protected void Page_Load(object sender, EventArgs e) {
    BLSecurity BLSecurity = new BLSecurity();

    BLSecurity.Gebruiker = (wk_Gebruiker)Session["gebruiker"];

    SomeFunction();
}

在函数 SomeFunction(); 中我需要那些方法。

SomeFunction();

private void SomeFunction(){
    BLSecurity BLSecurity = new BLSecurity();      //here lies the problem

    if(BLSecurity.IsLoggedIn()){
        ...
    } else {
        ...
    }
}

所以问题是 DoSomething()

中的这个新的 BLSecurity 实例

解决方案是将实例移动到 Page_Load()

上方
public partial class WineKeeper : System.Web.UI.MasterPage {

    private BLSecurity BLSecurity = new BLSecurity();

    protected void Page_Load(object sender, EventArgs e) {
        BLSecurity.Gebruiker = (wk_Gebruiker)Session["gebruiker"];
        SomeFunction();
    }
}

这样我就不会被重写而导致 null。

很高兴您找到了答案。我想指出的是,您不应该将变量命名为与 class 名称完全相同的名称。

而不是这个:

BLSecurity BLSecurity = new BLSecurity();

你应该做更多这样的事情:

BLSecurity blSecurity = new BLSecurity();

在这种情况下它可能对你有用,但根据经验,这是不好的做法,因为你可能会遇到歧义错误。