簡體   English   中英

訪問列表中包含的對象的特定屬性 <Object> 在C#中

[英]Access specific properties of an object contained within a List<Object> in C#

我似乎無法弄清楚如何訪問列表中包含的每個對象的特定屬性。 例如,如果我引用列表之外的對象(在將其傳遞給按鈕單擊之前),則可以看到諸如“標簽”,“高度”,“寬度”等之類的屬性(該類型的所有標准屬性) )。 但是,將列表傳遞給按鈕單擊事件后,我無法弄清楚如何訪問那些特定於對象的屬性。

請參考以下示例:

private TextBox createTextBox(string name)
{
    // Create TextBox Code is Here
    TextBox dTextBox = new TextBox();
    dTextBox.Name = name;
    dTextBox.Tag = "sometag";
    dTextBox.Height = 12345;
    dTextBox.Width = 12345;
    return dTextBox;
}

private void some_function()
{
    var objectList = new List<Object>();
    objectList.Add(createTextBox("example1"));
    objectList.Add(createTextBox("example2"));
    objectList.Add(createTextBox("example3"));
}

private int button_click(object sender, EventArgs e, Int32 ticketGroupID, List<Object> objectList)
{
    for(int i = 0; i < objectList.Count(); i++)
    {
        Int32 valuableInfo = objectList[i].?? // Here is where I am trying to access specific properties about the object at index i in the list, such as the objects TAG, VALUE, etc. How can this be done?
        // do things with the valuable info
    };

}

在此先感謝您的協助。

您需要使object強類型。 也就是說,將其轉換為您的class

Int32 valuableInfo = ((TextBox)objectList[i]).Height; //now you can access your property

否則,您將無法訪問類的屬性,因為編譯器將不知道object的實際類型是什么。 另外,您的Intellisense只會將其視為object ,而不是您的強類型類(例如: MyClass ,或者在您的情況下,該類為TextBox

這是一個實現IEnumerable<T>List <> ,因此您可以使用OfType<T>()方法來提取已經強類型化並可以訪問的項目:

var myListOfTypedObjects = myList.OfType<TextBox>();
myListOfTypedObjects.ForEach(tb => Console.Writeline(tb.Name));

您可以先檢查type ,然后再將其TextBoxTextBox反向

請參見下面的示例:

foreach (var obj in objectList)
{
    // method 1: check first, cast later
    if (obj is TextBox)
    {
        Int32 valueableInfo = ((TextBox)obj).Height;
    }

    // method2: cast first, check later
    var textBox = obj as TextBox;
    if (obj != null)
    {
        Int32 valueableInfo = obj.Height;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM