C#铸造类型与类型名得到的字符串
问题描述:
我要解决的事实,我的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的类型的非对象类型的版本(我不知道怎么说这完全一致)
答
您不需要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 });
}
+0
错!如果你甚至不尝试编译它,请停止提供不正确的答案...... – leppie 2009-07-27 10:06:23
答
我想我也有类似问题的线条,这样做是有点乱:别人的
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();
对更好的解决方案感兴趣。
`typeof`是一个编译时构造。在你的情况下`typeof(T)`是`Type`。您正在混合编译时和运行时的东西。 – 2009-07-27 10:08:06