C#问题:我如何使用构造函数:
AcctHolder ah1 = new AcctHolder("Dumitru", "St", "Bucharest");
并且能够获得ah1.Fname
? (而不是null)
using System;
namespace ConsoleApplication1
{
class ATM
{
public static void Main(string[] args)
{
AcctHolder ah1 = new AcctHolder("Dumitru", "St", "Bucharest");
Console.WriteLine(ah1.FName); //returns null - why???
AcctHolder ah2 = new AcctHolder();
ah2.FName = "Dumi";
Console.WriteLine(ah2.FName); // returns "Dumi"
Console.ReadKey();
}
public class AcctHolder
{
private string fname, lname, city;
public string FName { get; set; }
public string LName { get; set; }
public string City {
get { return city; }
set { city = value; }
}
public AcctHolder(string a, string b, string c)
{
fname = a;
lname = b;
city = c;
}
public AcctHolder()
{
}
}
}
}
答案 0 :(得分:10)
返回null - 为什么???
因为您正在构造函数中初始化不相关的字段而不是属性的支持字段。你不需要auto-implemented properties:
public class AcctHolder
{
public string FName { get; set; }
public string LName { get; set; }
public string City { get; set; }
public AcctHolder(string a, string b, string c)
{
FName = a;
LName = b;
City = c;
}
public AcctHolder()
{
}
}
如果您想保留支持字段:
public class AcctHolder
{
private string fname;
public string FName
{
get { return fname; }
set { fname = value; }
}
private string lname;
public string LName
{
get { return lname; }
set { lname = value; }
}
private string city;
public string City
{
get { return city; }
set { city = value; }
}
public AcctHolder(string a, string b, string c)
{
fname = a;
lname = b;
city = c;
}
public AcctHolder()
{
}
}
答案 1 :(得分:4)
您在构造函数中设置了错误的(私有)fname
。使用公开。
变化
public AcctHolder(string a, string b, string c)
{
fname = a;
lname = b;
city = c;
}
到
public AcctHolder(string a, string b, string c)
{
Fname = a;
LName = b;
City = c;
}
答案 2 :(得分:2)
在构造函数中,设置
FName = a;
而不是
fname = a;
属性FName
和LName
不需要支持字段,因为您使用get;set;
- 语法来声明它们。他们会自动获取,因此您只需从代码中完全删除fname
和lname
即可。
答案 3 :(得分:2)
由于您使用自动属性,因此不需要私有字段。简化:
public class AcctHolder
{
public string FName { get; set; }
public string LName { get; set; }
public string City { get;set;}
public AcctHolder(string a, string b, string c)
{
FName = a;
LName = b;
City = c;
}
public AcctHolder()
{
}
}
答案 4 :(得分:1)
或者,更改类以使用与City相同的私有字符串。
public class AcctHolder
{
private string fname, lname, city;
public string FName { get {return fname;} set {fname = value; }
public string LName { get {return lname;} set {lname = value;} }