c# - 将类型转换为通用约束 T

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

最佳答案

使用:

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

代替:

if (i_FeatureType is T)

关于c# - 将类型转换为通用约束 T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12053161/

相关文章:

c# - MVVM 事件处理程序属于哪里

c# - 使用泛型更新特定属性 (Winform C#)

python - 是否可以用 True 初始化 bool?

Scala 类型检查/断言作为函数 vs JVM 类型删除

c# - 使用不同的兼容类型覆盖属性

mysql - 由于数据类型, '' 中的未知列 'field list'

C#/SQL 错误 : There was an error parsing the query. [ token 行号 = 1, token 行偏移量 = 26,错误中的 token = 用户 ]

c# - WPF 绑定(bind) View 作为内容

c# - 尝试在 .NET 中使用 EventLog.SourceExists 方法时出现问题

c# - 使用泛型创建可重用的 Control 基类