[英]How to use a C# Object Array as a Property
I can use this snippet: 我可以使用以下代码段:
public object Obj
{
get;
set;
}
Like this: 像这样:
public fubar()
{
...
Obj = SomeObject;
}
But cannot seem to use this snippet: 但似乎无法使用此代码段:
public object[] ObjectAsArray
{
get;
set;
}
Like this or any other way I have tried so far: 像这样或到目前为止我尝试过的任何其他方式:
public fubar()
{
...
Obj[n] = SomeObject;
//or
var x = Obj[0] as SomeObject;
//or other ways...
}
I seem to be missing something here. 我似乎在这里错过了一些东西。
Can somebody give a simple example of the correct declaration of a C# property that is of type object[]
and consumption thereof? 有人可以给出一个简单的示例来正确声明类型为
object[]
的C#属性及其用法吗?
As soon as you change it from Obj
to ObjectAsArray
it should compile. 一旦将其从
Obj
更改为ObjectAsArray
它就应该编译。 You'll still need to actually create the array though: 您仍然需要实际创建数组:
ObjectAsArray = new object[10];
ObjectAsArray[5] = "Hello";
You're trying to set Obj[n]
before Obj
itself is initialized... so, I imagine you're getting a null-reference exception. 您正在尝试在
Obj
本身初始化之前设置Obj[n]
。因此,我想您会收到一个空引用异常。 You need to perform an assignment, like so: 您需要执行任务,如下所示:
Obj = new Object[];
... and in context: ...并且在上下文中:
public fubar()
{
Obj = new Object[13]{}; // where 13 is the number of elements
Obj[n] = SomeObject;
}
I would suggest adding a private backing field for the object[] property and initialize it - either directly or in the getter. 我建议为object []属性添加一个私有后备字段,并直接或在getter中对其进行初始化。
object[] _objectsAsArray = new object[10];
OR 要么
public object[] ObjectAsArray
{
get
{
if(_objectsAsArray == null)
_objectsAsArray = new object[10];
return _objectsAsArray;
}
set
{
_objectsAsArray = value;
}
}
The complier is creating a private backing field anyhow so why not be explicit about it. 编译器无论如何都会创建一个私有的支持字段,所以为什么不明确说明它。 Also, auto-implemented properties have some drawbacks (serialization, threading, etc).
同样,自动实现的属性也有一些缺点(序列化,线程化等)。 Doing it the "old-fashioned" way also gives you a nice place to actually create the array.
以“老式”方式进行操作还为您提供了一个实际创建数组的好地方。 Of course if you don't need to worry these issues - go ahead and use the auto-implemented property.
当然,如果您不必担心这些问题,请继续使用自动实现的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.