[英]Convert a Type to a Generic constrained T
我正在嘗試建立一個工廠,它將提供單一的工廠方法。 在這個方法中,我想驗證傳入的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)
您正在將對象與“類型”對象進行比較。
所以,而不是
if(i_FeatureType為T)
嘗試
if(i_FeatureType == typeof(T))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.