2009-07-27 78 views
2

我要解決的事實,我的WCF servicelayer不能處理這樣的通用方法:C#鑄造類型與類型名得到的字符串

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); 
} 

問題是這不能以某種方式編譯。

我覺得這是我的不完全理解

  • T型 之間的差別,我相信這是一個類型「類型」

  • typeof運算的結果的對象的結果(T ) 我相信這會導致T的類型的非對象類型的版本(我不知道怎麼說這完全一致)

+0

`typeof`是一個編譯時構造。在你的情況下`typeof(T)`是`Type`。您正在混合編譯時和運行時的東西。 – 2009-07-27 10:08:06

回答

7

您不需要typeName:您必須傳遞Type實例,或使用object.GetType()來檢索對象運行時類型。

在這兩種情況下,

MethodInfo genericSaveMethod = domainRoot.GetType().GetMethod("SaveDomainObject"); 
MethodInfo closedSaveMethod = genericSaveMethod .MakeGenericMethod(domainObject.GetType()); 
closedSaveMethod.Invoke(domainRoot, new object[] { domainObject }); 
0

不幸的是,這樣的事情是很困難的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 }); 
} 
+0

錯!如果你甚至不嘗試編譯它,請停止提供不正確的答案...... – leppie 2009-07-27 10:06:23

0

我想我也有類似問題的線條,這樣做是有點亂:別人的

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(); 

對更好的解決方案感興趣。