问题
Excuse me, this question maybe exist in a different form but I really searched everywhere and don't see it.
I have worked in C++ and am used to pointers. I am having problem with substituting my logic with C# analogue code.
Here is my C# code:
class Parent
{
public Parent A { get; set; }
public Parent B { get; set; }
}
static void Main(string[] args)
{
Parent P1 = new Parent();
Parent X = new Parent();
Parent[] array = new Parent[10];
array[0] = P1;
array[1] = P1.A;
array[2] = P1.B;
array[1]= X;
//I expect P1.A to be X but it is null
}
I have seen that there are pointers in C# but is there a better way to do this? Thanks
Edit:
My question wasn't complete. I am sorry. This is the code:
abstract class Parent
{
protected virtual int foo();
}
public class Son : Parent
{
public Parent A { get; set; }
public Parent B { get; set; }
protected override int foo()
{
return base.foo();
}
}
public class Daughter : Parent
{
public Parent A { get; set; }
public Parent B { get; set; }
}
static void Main(string[] args)
{
Son P1 = new Son();
Parent X = new Daughter();
Parent[] array = new Parent[10];
array[0] = P1;
array[1] = P1.A;
array[2] = P1.B;
array[1]= X;
//I expect P1.A to be X but it is null
}
回答1:
What you wan t to do is:
array[1].A = X;
回答2:
It is null because it isn't initialized.
You must initialize properties.
class Parent
{
public Parent A { get; set; }
public Parent B { get; set; }
Parent(Parent a, Parent b)
{
A = a;
B = b;
}
}
and
Parent X = new Parent();
Parent P1 = new Parent(X, new Parent());
来源:https://stackoverflow.com/questions/33566922/adding-an-instance-to-reference-that-is-field-in-another-instance