juergen d
juergen d

Reputation: 204894

Compare types in base class

I have a Part base class

class Part {
    public PartType Type { get; set; }
}

with many implementations.

class Wire : Part {   }

I have a TreeView in my program. And when I click on an element of it, I want a list to be filled with all the Parts of the Type I clicked in the TreeView.

When I have multiple lists open I want only those be loading the parts that have the same PartType as I clicked in the TreeView.

class BasePartListViewModel<T> : ListViewModel where T : Part {
    protected override void OnTreeSelectionChanged(PartType type)
        if (type == PartType.Wire) {
            //load the Wires from the DB and display them
        } 
        else {
            //ignore the changed type event
        }
    }
}

But since this is a base class for all Parts by using T I would like to replace

if (_type == PartTypeEnum.Wire)

with something like

if (_type == T.Type)

but that does of course not work. How else?

Upvotes: 0

Views: 97

Answers (2)

Dmitry
Dmitry

Reputation: 14059

Since the part type is a static information for a class type by design (am I right?), you could use an attribute to store it:

[AttributeUsage(AttributeTargets.Class)]
public class PartTypeAttribute : Attribute
{
    public readonly PartType PartType;

    public PartTypeAttribute(PartType partType)
    {
        PartType = partType;
    }
}

Then apply it to the descendant classes:

[PartType(PartType.Wire)]
class Wire : Part
{
}

Then in the static constructor of the BasePartListViewModel class you can obtian the corresponding value:

class BasePartListViewModel<T> : ListViewModel
    where T : Part
{
    private static PartType PartTypeOfT;

    static BasePartListViewModel()
    {
        var attr = typeof(T).GetCustomAttributes(typeof(PartTypeAttribute), true)
            .FirstOrDefault() as PartTypeAttribute;
        if (attr != null)
            PartTypeOfT = attr.PartType;
    }

    protected override void OnTreeSelectionChanged(PartType type)
    {
        if (type == PartTypeOfT) {
            ....
        }
    }
}

Upvotes: 4

Ashraff Ali Wahab
Ashraff Ali Wahab

Reputation: 1108

If you do this.GetType() it will return as BasePartListViewModel`1[Wire]

You should not be ideally referring this in the base class.

Upvotes: -2

Related Questions