-3

如何声明索引属性?

public class PublishProperties : ScriptableObject {

List<string> m_shellPathsT = new List<string>();
List<string> m_shellPathsL = new List<string>();
public List<string> ShellPath[int index]
{
    get 
    {
        if (index == 0)
            return m_shellPathsT;
        else
            return m_shellPathsL;
    }
}

这不会编译,我不确定如何编码。由于其他要求,我必须拥有两个这样声明的不同列表。

我通常会有一个列表数组......

或者像这样

public List<string>[] m_shellPaths = { new List<string>(), new List<string>() };

但是,这再次不适用于其他因素......(基本上有一些自动发生的序列化不适用于构造函数中声明的变量或类似上面的变量。)

4

3 回答 3

1

请在提问之前阅读文档。

public List<string> this[int index]
{
    get 
    {
        if (index == 0)
            return m_shellPathsT;
        else
            return m_shellPathsL;
    }
}
于 2013-02-19T23:37:00.183 回答
0

Based on your comments, it seems you want to access items of either m_shellPathsT or m_shellPathsS via ShellPaths.

So, assuming foo is an object of type PublishProperties, you want to be able to write code like this:

foo.ShellPaths[0];

What happens here is actually two things:

  1. You are accessing property ShellPaths on type PublishProperties. It returns a List<string>
  2. You are accessing the item at index 0 of the returned list. It returns a string.

The property ShellPaths has the following structure:

public List<string> ShellPaths
{
    get { return <something>; }
}

As you can see, there is no index.

But because you want to access different lists based on the index, the implementation of ShellPaths can't simply return either one of your internally stored lists.

You will have to create a new list that returns the first item of m_shellPathsT if the index is 0. Otherwise it returns the corresponding item of m_shellPathsS.

To achieve this, you could implement ShellPaths like this:

public List<string> ShellPaths
{
    get { return m_shellPathsT.Take(1).Concat(m_shellPathsS.Skip(1)).ToList(); }
}

Now, that would work, but would be quite unefficient: Every time someone accesses ShellPaths a new list is created. It would be better if you would create that special list once, maybe in the constructor or whenever the content of any of the internal lists changes.

于 2013-02-20T07:44:12.487 回答
0

C# 不支持索引属性。您可以使用索引类本身

public List<string> this[int index]
{
    get 
    {
        if (index == 0)
            return m_shellPathsT;
        else
            return m_shellPathsL;
    }
}

但是在这个非常特殊的情况下,我无法这样做,因为需要几组这种类型的实现,并且序列化使我无法使用更优雅的声明。

可以使用方法,但不具有与属性相同的功能。
我找到了有关此的更多信息

但是在这种情况下,我没有理由不能添加一个额外的数组

public List<string> m_shellPathsT = new List<string>();
public List<string> m_shellPathsL = new List<string>() ;
public List<string>[] m_shellPaths = new List<string>[2];

public PublishProperties()
{
    m_shellPaths[0] = m_shellPathsT;
    m_shellPaths[1] = m_shellPathsL;
}
于 2013-02-20T00:30:39.240 回答