gpt4 book ai didi

c# - 需要有关属性(property)使用权的进修类(class)

转载 作者:行者123 更新时间:2023-11-30 15:10:53 24 4
gpt4 key购买 nike

我需要帮助来访问给定类中的类属性。

例如,参加下面的类(class):

public partial class Account
{
private Profile _profile;
private Email _email;
private HostInfo _hostInfo;

public Profile Profile
{
get { return _profile; }
set { _profile = value; }
}

public Email Email
{
get { return _email; }
set { _email = value; }
}

public HostInfo HostInfo
{
get { return _hostInfo; }
set { _hostInfo = value; }
}

在类“Account”中存在一堆类属性,例如电子邮件或配置文件。现在,当我想在运行时访问这些属性时,我会做这样的事情(对于电子邮件):

    _accountRepository = ObjectFactory.GetInstance<IAccountRepository>();
string username = Cryptography.Decrypt(_webContext.UserNameToVerify, "verify");
Account account = _accountRepository.GetAccountByUserName(username);

if(account != null)
{
account.Email.IsConfirmed = true;

但是,我收到 account.Email 的“未设置对象引用...”...这是为什么?如何访问诸如 account.Email、account.Profile 等帐户返回给定 AccountId 或 UserName 的正确数据。

    Here is a method that returns Account:

public Account GetAccountByUserName(string userName)
{
Account account = null;

using (MyDataContext dc = _conn.GetContext())
{
try
{
account = (from a in dc.Accounts
where a.UserName == userName
select a).FirstOrDefault();
}
catch
{
//oops
}
}

return account;

}

上面的工作但是当我尝试时:

 account = (from a in dc.Accounts
join em in dc.Emails on a.AccountId equals em.AccountId
join p in dc.Profiles on em.AccountId equals p.AccountId
where a.UserName == userName
select a).FirstOrDefault();

我的电子邮件和个人资料仍然收到对象引用异常
特性。这只是一个 SQL 问题还是我需要做的其他事情做什么才能完全访问我的帐户类中的所有属性?

谢谢!

最佳答案

你得到这个是因为电子邮件是另一个尚未分配的类。你可以做的是在你的构造函数中默认链接到其他类的属性作为新项目。例如在你的 ctor 中:

public Account()
{
// Set Defaults
Email = new Email();
Profile = new Profile();
HostInfo = new HostInfo();
}

然后您可以根据需要设置它们的值。

关于c# - 需要有关属性(property)使用权的进修类(class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2915035/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com