简体   繁体   中英

Convert a Type to a Generic constrained T

I am trying to build a Factory which will supply a single factory method. In this method I want to verify whether the incoming Type is the factory's T.

What I've written is simply not working. I believe I understand the reason for it's failure, yet I am not sure how to form my casting correctly.

Below is my code. Any ideas as for how to form this condition/casting?

    public T GetFeature(Type i_FeatureType, User i_UserContext)
    {
        T typeToGet = null;

        if (i_FeatureType is T) // <--condition fails here
        {
            if (m_FeaturesCollection.TryGetValue(i_FeatureType, out typeToGet))
            {
                typeToGet.LoggenInUser = i_UserContext;
            }
            else
            {
                addTypeToCollection(i_FeatureType as T, i_UserContext);
                m_FeaturesCollection.TryGetValue(typeof(T), out typeToGet);
                typeToGet.LoggenInUser = i_UserContext;
            }
        }

        return typeToGet;
    }

Use:

 if (typeof(T).IsAssignableFrom(i_FeatureType))

Instead of:

if (i_FeatureType is T)

You are comparing your objects with a 'Type' object.

So, instead of

if (i_FeatureType is T)

try

if (i_FeatureType == typeof(T))

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