![](/img/trans.png)
[英]Type casting from IEnumerable to ObservableCollection in C#
[英]c# casting to type gotten from typename as string
我想解決以下事實:我的WCF服務層無法處理這樣的通用方法:
public void SaveOrUpdateDomainObject<T>(T domainObject)
{
domainRoot.SaveDomainObject<T>(domainObject);
}
所以我建立了這種解決方法
public void SaveOrUpdateDomainObject(object domainObject, string typeName)
{
Type T = Type.GetType(typeName);
var o = (typeof(T))domainObject;
domainRoot.SaveDomainObject<typeof(T)>(o);
}
問題是這無法以某種方式編譯。
我認為這是我沒有完全了解兩者之間的區別的結果
TI類型相信這是“ Type”類型的對象
typeof(T)的結果,我相信這會導致T類型的非對象類型版本(我不知道該怎么說)
您不需要typeName
:您必須傳遞Type
實例,或者使用object.GetType()
來檢索對象運行時類型。
在任一情況下,
MethodInfo genericSaveMethod = domainRoot.GetType().GetMethod("SaveDomainObject");
MethodInfo closedSaveMethod = genericSaveMethod .MakeGenericMethod(domainObject.GetType());
closedSaveMethod.Invoke(domainRoot, new object[] { domainObject });
不幸的是,在C#中,這樣的事情相當困難。 就像您從字符串中獲取正確的Type實例一樣容易,但是您必須使用反射來獲取正確的方法。
嘗試一些類似的方法
public void SaveOrUpdateDomainObject(object domainObject, string typeName)
{
Type T = Type.GetType(typeName);
MethodInfo genericMethod = domainRoot.GetType().GetMethod("SaveDomainObject");
MethodInfo method = genericMethod.MakeGenericMethod(T);
method.Invoke(domainRoot, new object[] { domainObject });
}
我認為我有一個類似的問題,但是這樣做有點混亂:
if (businessObject is Made4Print.Country)
((Made4Print.Country)businessObject).Save();
else if (businessObject is Made4Print.User)
((Made4Print.User)businessObject).Save();
...其他人的負擔...
else if (businessObject is Made4Print.Timezone)
((Made4Print.Timezone)businessObject).Save();
會對更好的解決方案感興趣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.