문제

I have a TreeView of TreeNode with various TreeNode.Tag types.

To assign the TreeNode.Tag I instantiate a struct with data and do aTreeNode.Tag = aStruct; I have three different structs StructOne, StructTwo, and StructThree.

So a TreeNode.Tag can be one of those three types of struct. I want to write a switch statement based on the TreeNode.Tag type.

I am not sure how to determine the type of the .Tag though. I have tried this

if(aTreeNode.Tag is typeof(StructOne))

but my IDE (MVS) tells me "Type Expected". Do struct not have a types in C#?

I also think this could be achieved with a try{]catch{} block, but I think there is a cleaner solution?

EDIT: For more background, the .Tag structs hold information about the forms they represent. So when a user clicks on a TreeNode I need to determine what type of window to open, so for each TreeNode.Tag I attach a little bit of data about the window to open and some other things about what goes in the window. But I have three different types of forms, and below those other sub types of forms.

도움이 되었습니까?

해결책

If you don't have to use structs and can use classes. I would suggest the polymorphism approach of:

public interface ICanDoStuff
{
    void DoStuff();
}

public class OnOfMyTagClasses : ICanDoStuff
{
    public void DoStuff()
    {
      //Do some stuff
    }
}

((ICanDoStuff)aTreeNode.Tag).DoStuff();

Instead of using a switch-case.

다른 팁

Try the following:

if (aTreeNode.Tag is StructOne)

typeof(SOME_TYPE_NAME) is a runtime type reference (of type System.Type).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top