将Type转换为Generic约束T

时间:2012-08-21 10:41:15

标签: c# generics types casting factory-pattern

我正在尝试构建一个工厂,它将提供单一的工厂方法。 在这个方法中,我想验证传入的Type是否是工厂的T。

我所写的内容根本就不起作用。我相信我理解它失败的原因,但我不确定如何正确地形成我的演员。

以下是我的代码。关于如何形成这种条件/铸造的任何想法?

    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;
    }

2 个答案:

答案 0 :(得分:4)

使用:

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

而不是:

if (i_FeatureType is T)

答案 1 :(得分:0)

您正在将对象与“类型”对象进行比较。

所以,而不是

if(i_FeatureType为T)

if(i_FeatureType == typeof(T))

相关问题