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

标签 c# properties

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

例如,参加下面的类(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/

相关文章:

java - 在 Java 中使用 Spring 动态加载属性

java.util.Properties$LineReader.readLine

objective-c - 没有显式声明的属性 ivars 会生成哪些名称?

c# - Fluent Validation - 当特定验证失败时停止验证所有其他验证

c# - 如何声明多个计时器并在时间到期时停止计时器

c# - 如何在字段包含 char ' 的 Access 中运行查询

java - 我应该使用什么属性文件库来处理数组和字符串,并使用简单的代码?

spring - 在 applicationContext.xml Spring 文件中存储自定义属性

c# - 使用数据绑定(bind)的 C#/WPF 中具有确定/取消行为的对话框

c# - .Net 3.5 VS 2008 无效 token 'out' 错误