My Code:
public class A
{
public virtual void displayDetailInfo()
{
}
}
public class B : A
{
public String _a;
public int _n;
public B() { }
public B(String _a, int _n)
{
this._a = _a;
this._n = _n;
}
public String A
{
get { return _a; }
set { this._a = value; }
}
public int N
{
get { return _n; }
set { this._n = value; }
}
public override void displayDetailInfo()
{
Console.WriteLine(A);//To obtain value entered in Main(i.e. f.A)
Console.WriteLine(N);//To obtain value entered in Main(i.e. f.N)
}
}
public class Program
{
public static void Main(String[] args)
{
A v = new A();
A v1 = new B();
B f = new B();
f.A = Console.ReadLine(); //Value to be accessed
f.N = Convert.ToInt32(Console.ReadLine()); //Value to be accessed
v1.displayDetailInfo();
}
}
How can I get the value(f.A and f.N) I entered in Main accessed from the overrided method in class B(i.e. displayDetailInfo()). The code I wrote doesn't obtains any value(i.e. Console.WriteLine(A) gives no value of f.A). So how can I get the value of f.A and f.N from overrided displayDetailInfo()?
答案 0 :(得分:0)
You can't do this because you v1
is a different instance of B
than the one you want to get the values from (f
)
Calling f.displayDetailInfo()
should give you the result you want
答案 1 :(得分:0)
You are setting A of a different object than what you are calling displayDetailInfo on. I think you meant to do this:
public static void Main(String[] args)
{
A v = new Vehicle();
B v1 = new B();
v1.A = Console.ReadLine(); //Value to be accessed
v1.N = Convert.ToInt32(Console.ReadLine()); //Value to be accessed
v1.displayDetailInfo();
}
答案 2 :(得分:0)
v1
无法包含您在f
中输入的数据。该类只是一个蓝图,v1
和f
是存在于堆的不同部分的不同实例。
v1.A
与f.A
不同,v1.N
与f.N
要查看您输入的值,最好拨打:
f.displayDetailInfo()
此外,您使用的属性错误。如果要使用支持字段,带有下划线(_n
和_a
)的字段,最好将它们设为私有字段。除非你想为getter或setter提供额外的逻辑,否则最好不要完全使用支持字段并使用自动实现的属性:
public string A { get; set; }
public string N { get; set; }
答案 3 :(得分:0)
每当您使用new
创建新对象时,您将创建一个具有自己状态的新的独立对象。
在这里,您要创建3个单独的对象 - v
,v1
,f
。
A v = new Vehicle();
A v1 = new B();
B f = new B();
更改其中一个对象的属性不会影响其他两个对象的属性。
您可以在此处更改f
的属性,但不会影响v1
的属性。
f.A = Console.ReadLine();
f.N = Convert.ToInt32(Console.ReadLine());
这就是为什么当你调用v1.displayDetailInfo()
时,它会打印null和0. null和0分别是string
和int
的默认值。 v1
的属性尚未设置,因此它们保留默认值。
要解决此问题,请改为调用f.displayDetailInfo()
。