我正在尝试构建一个提供单一工厂方法的工厂。 在这个方法中我想验证传入的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/