本文介绍了添加一个实例引用是在另一个实例字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对不起,这个问题可能存在于不同的形式,但我真的到处搜寻,并没有看到它。
我在C ++中工作过并习惯了指针。我有与C#模拟code代替我的逻辑问题。
下面是我的C#code:
类父
{
公共父{搞定;组; }
公共父B {搞定;组; } } 静态无效的主要(字串[] args)
{ 家长P1 =新的父();
家长X =新的父();
家长[]数组=新的父[10];
数组[0] = P1;
阵列[1] = P1.A;
数组[2] = P1.B; 阵列[1] = X; //我希望P1.A是X,但它为空
}
我曾经看到有在C#中三分球,但有没有更好的方式来做到这一点?谢谢
编辑:
我的问题是不完整的。对不起。这是code:
抽象类父
{ 保护虚拟INT富();
} 公共类儿子:父
{
公共父{搞定;组; }
公共父B {搞定;组; } 保护覆盖INT富()
{
返回base.foo();
} } 公共类女儿:父母
{
公共父{搞定;组; }
公共父B {搞定;组; }
} 静态无效的主要(字串[] args)
{ 儿子P1 =新的子();
家长X =新媳妇();
家长[]数组=新的父[10];
数组[0] = P1;
阵列[1] = P1.A;
数组[2] = P1.B; 阵列[1] = X; //我希望P1.A是X,但它为空
}
解决方案
这是空,因为它未初始化。
您必须初始化属性。
类父
{
公共父{搞定;组; }
公共父B {搞定;组; } 父(父,母二)
{
A = A;
B =;
}
}
和
父X =新的父();
家长P1 =新的父(X,新的父());
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
}
解决方案
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());
这篇关于添加一个实例引用是在另一个实例字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!