[英]C# property for fields with user-defined class type
First, define a class named AAA:首先,定义一个名为 AAA 的 class:
class AAA
{
public int a = 1;
}
Then, define another class BBB contains a field with type AAA (a property A for that field, and the field has been initialized, namely, not null):然后再定义一个 class BBB 包含一个类型为 AAA 的字段(该字段的属性 A,并且该字段已经初始化,即不为空):
class BBB
{
private AAA a = new AAA();
public AAA A { set; get; }
public bool isNull()
{
return a == null;
}
}
Next, I wrote the code below outside:接下来,我在外面写了下面的代码:
BBB b = new BBB();
var flag = b.isNull(); // the value is FALSE
b.A.a = 3; // NullPointerException
As is stated in the comment above, b.isNull() returns FALSE.如上面的评论所述,b.isNull() 返回 FALSE。 So, the field a is not null. However, the 3rd line (bAa = 3) throws a NullPointerException.
因此,字段 a 不是 null。但是,第 3 行 (bAa = 3) 抛出 NullPointerException。
If property A can get the pointer (C# has no pointer, I mean the address references to the real object a) of the field a, this exception should not be thrown.如果属性A可以得到字段a的指针(C#没有指针,我指的是指向真实object a的地址引用),则不应抛出该异常。
My question is whether it would be possible to get an object using property in C#.我的问题是是否有可能使用 C# 中的属性获得 object。
Because you have initialized a
not A
.因为你已经初始化
a
not A
。 bA
is null
. bA
是null
。
But I am not sure what are you trying to achieve by declaring a
and A
with the same type.但我不确定你想通过声明相同类型
a
和A
来实现什么。
I don't think you need to declare A
in your case.我认为您不需要在您的情况下声明
A
And please provide a meaningful name to the class instead of A
.. B
..请为 class 提供一个有意义的名称,而不是
A
.. B
..
Here you go as per my comment here is the fix.在这里你 go 根据我在这里的评论是修复。 Keeping in mind your question is not clear so this is what I assume you want.
请记住,您的问题不清楚,所以这就是我认为您想要的。 class BBB {
class BBB {
public BBB()
{
A = new AAA();
}
public AAA A { set; get; }
public bool isNull()
{
return A == null;} //will always return false
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.