在C#中,是否可以使用数组属性?

时间:2020-04-13 09:45:07

标签: c# unity3d properties

据我所知,C#属性是具有getset访问器的方法。

class MyClass  
{  
    private int x;  
    public int X  
    {  
        get  
        {  
            return x;  
        }  
        set  
        {  
            x = value;  
        }  
    }  
}  

我可以使用

在脚本(及其访问器)中调用类的属性
MyClass mc = new MyClass();
mc.X = 10;
Debug.Log(mc.X); //returns 10

据我所知,我只能将一个值传递给属性。
有没有办法传递数组?像

MyClass mc = new MyClass();
mc.X = new int[] { 1, 2 }; //throws an error
Debug.Log(mc.X[0]); //I'd like it to return 1

这当然会引发错误。我想知道是否可以通过其他方式进行。

2 个答案:

答案 0 :(得分:4)

解决方案很简单-使用int[]代替int

class MyClass
{
    private int[] x;
    public int[] X
    {
        get
        {
            return x;
        }
        set
        {
            x = value;
        }
    }
}

您也可以考虑使用auto属性,就像这样:

class MyClass
{
    public int[] X { get; set; }
}

您可能还想看看列表并阅读一些基础知识;)

答案 1 :(得分:3)

当然,只需将属性设置为数组或列表:

class MyClass  
{  
    // in general a list should never be null, but could be empty, or without values.
    // thats why we initialize the field here
    private List<int> x = new List<int>();  

    public List<int> X  
    {  
        get  
        {  
            return x;  
        }  
        set  
        {  
            x = value;  
        }  
    }  
}  

那么你可以做:


var obj = new MyClass();
obj.X.Add(3);
obj.X.Add(6);

// (or use AddRange() to add another list or array of values

// Then loop the list and output values:

foreach(int x in obj.X)
{
   Console.WriteLine(x);
}

以下是上面代码的dotnetfiddle: https://dotnetfiddle.net/T2FrQ0

相关问题