【问题标题】:Can I set a property for an array?我可以为数组设置属性吗?
【发布时间】:2011-04-26 22:36:59
【问题描述】:

目前我有一个变量和一个属性:

private System.Xml.Linq.XDocument myDoc;

public System.Xml.Linq.XDocument getMyDoc
        {
            get
            {
                return myDoc;
            }
            set
            {
                myDoc = value;
            }
        }

现在我需要两个文档:

private System.Xml.Linq.XDocument[] myDoc; // array with 2 or 3 XDocuments

我希望我能够获取或设置特定的数组元素:

get
{
return myDoc(0);
}
set 
{
myDoc(0)=value;
}

有可能吗?

如果这很重要...由于我使用的是多线程,因此我无法将所有信息集中在一处。

【问题讨论】:

    标签: .net multithreading arrays properties


    【解决方案1】:

    您可以将 docs 变量更改为数组,然后使用索引器:

    public class MyXmlDocument
    {
        private readonly System.Xml.Linq.XDocument[] docs;
    
        public MyXmlDocument(int size)
        {
            docs = new System.Xml.Linq.XDocument[size];
        }
    
        public System.Xml.Linq.XDocument this [int index]
        {
            get
            {
                return docs[index];
            }
            set
            {
                docs[index] = value;
            }
        }
    }
    
    static void Main(string[] args)
    {
        // create a new instance of MyXmlDocument which will hold 5 docs
        MyXmlDocument m = new MyXmlDocument(5);
    
        // use the indexer to set the element at position 0
        m[0] = new System.Xml.Linq.XDocument();
    
        // use the indexer to get the element at position 0
        System.Xml.Linq.XDocument d = m[0];
    }
    

    【讨论】:

    • 如何调用此属性?我不明白为什么有一个字符串而不是 XDocument 以及“this”代表什么。谢谢
    • @Asaf - 对不起字符串的事情,这是我的一个错误。我已经编辑了我的答案以包含一个完整的示例。
    • @scp:它看起来像一个集合:msdn.microsoft.com/en-us/library/6x16t2tx.aspx,它可以满足我的需求,但我如何在课堂上使用它?我应该将我的参数定义为我的新集合而不是 Xdocument 数组
    • @Asaf - 您可以使用集合或数组,这对索引器没有影响。我不确定如何回答您关于如何在课堂上使用它的问题。您可以只添加数组(或集合,如果您决定使用它)和索引器代码,如上所示,然后您应该能够在您的类中使用它。示例用法参考上面的 Main 方法。
    • @scp :这是第一次......它有效,但我不明白为什么。类中有很多属性,它是如何选择正确的......是否只有一个属性使用它,或者我可以使用类型和签名......太奇怪了,但是一个很好的答案谢谢
    猜你喜欢
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    • 2010-11-24
    • 1970-01-01
    相关资源
    最近更新 更多