简体   繁体   English

将Type转换为Generic约束T

[英]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. 在这个方法中,我想验证传入的Type是否是工厂的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) if(i_FeatureType为T)

try 尝试

if (i_FeatureType == typeof(T)) if(i_FeatureType == typeof(T))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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