【问题标题】:C# WPF Property type another class [duplicate]C# WPF 属性类型另一个类[重复]
【发布时间】:2015-08-31 13:54:33
【问题描述】:
public class StudentNames : INotifyPropertyChanged
{
   string firstname
   string surname

   public string FirstName
    {
        get
        {
            return firstname;
        }
        set
        {
            if (firstname != value)
            {
                firstname = value;
                OnPropertyChanged("FirstName");
            }
       }
    }

    public string Surname
    {
        get
        {
            return surname
        }
        set
        {
            if (surname != value)
            {
                surname = value;
                OnPropertyChanged("Surname");
            }
       }
    }
 }

public class StudentDetails : INotifyPropertyChanged
{
    string address StudentNames sn

    public string SN
    {
        get
        {
            return sn;
        }
        set
        {
            if (sn != value)
            {
                sn = value;
                OnPropertyChanged("SN");
            }
       }
    }

    public string Address
    {
        get
        {
            return address;
        }
        set
        {
            if (address != value)
            {
                address = value;
                OnPropertyChanged("Address");
            }
      }
    }
 }

在其他地方我有逻辑:

StudentDetails sd = new StudentDetails()
sd.StudentNames.FirstName = "John"//this part gives me a runtime error

它编译但我得到一个运行时错误:

“对象引用未设置为对象的实例。”

【问题讨论】:

  • snstring 还是StudentNames 的实例?不清楚。请格式化并更正您的代码。

标签: c# wpf class properties


【解决方案1】:

您的公共构造函数应如下所示:

public StudentDetails() {
  StudentNames = new StudentNames();
}

您遇到了错误,因为您没有设置对 StudentNames 字段的对象引用。 然后就可以了

var sd = new StudentDetails():
sd.StudentNames.FirstName = "John"

另外,下次你最好添加完整的类代码。

【讨论】:

  • ... 下次 OP 应该先进行搜索,这会产生众所周知的问题:stackoverflow.com/questions/4660142/…。然后 OP 应该遵循一个建议:使用调试器......抱歉有点愤世嫉俗。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-19
  • 2013-03-07
  • 1970-01-01
  • 2021-04-02
  • 1970-01-01
相关资源
最近更新 更多