简体   繁体   中英

Declare variable of different type using If Else-If statement

I have a method which receives events based on which item is clicked within a TreeView.

I can add items to both a TreeView and a TreeViewItem in exactly the same way so have attempted to assign item as either TreeView or TreeViewItem based on the state.sender type. However, currently the only way I can make it work is to assign item as an object first.

private void ProcessEvent(Events.GetEventsResp resp, CustomAsyncStateContainer state)
{
    object item = new object();   //must be a better way than this?
    if (state.sender is TreeViewItem)
        item = (TreeViewItem)state.sender;

    else if (state.sender is TreeView)
        item = (TreeView)state.sender;

     //other code
}

I assume this is called unboxing? Is there a better way to do what I'm attempting?

Edit: Below is the remaining code. I hadn't finished writing it when asking the question and have now realised that object item = new object(); is not going to work in this case.

private void DisplayGetEvent(Events.GetEventsResp resp, CustomAsyncStateContainer state)
{
    object node = new object();
    if (state.sender is TreeViewItem)
        node = (TreeViewItem)state.sender;

    else if (state.sender is TreeView)
        node = (TreeView)state.sender;

    if (resp.eventItems != null)
    {
        Events.UXEvent[] eventItems = resp.eventItems;
        Array.Sort(eventItems, new UXWrapper.UXEventComparer());

        int itemCount = eventItems.Length;
        TreeViewItem tvItem = new TreeViewItem;
        for (int i = 0; i < itemCount; i++)
        {

            tvItem.Header = eventItems[i].name;
            tvItem.Tag = eventItems[i];

            node.Items.Add(tvItem);

        }

    }
}

TreeView and TreeViewItem both derive from ItemsControl , and adding items is done using the methods already available on that, so you should be able to simply use

private void ProcessEvent(Events.GetEventsResp resp, CustomAsyncStateContainer state)
{
    var item = (ItemsControl)state.sender;

    // add to item
}

Depending on your version of C#, you may be able to use the new dynamic type:
http://msdn.microsoft.com/en-us/library/dd264736.aspx

I agree with the other commenters that your problem description is insufficient, but if what you want to do is treat TreeView/TreeViewItem polymorphically, you could simply use a variable of type ItemsControl.

if (state.sender is ItemsControl)
    item = (TreeViewItem)state.sender;

else
    throw InvalidArgumentException("state.sender")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM